Matplotlib折线图X轴起始位置调整及时间周期缩短求助
问题解决:调整疫苗接种折线图的起始时间与图表时间区间
需求说明
需要将代表「Total Vaccinated」的红线起始位置从「FEB-2020」调整至「JAN-2021」,同时将整个图表的时间周期缩短到该日期区间,此前尝试过日期筛选和图表平移的方法但未生效。
当前代码
# plot daily vaccinated fig, ax1= plt.subplots(1,figsize=(20,10)) # set up plt.ticklabel_format(style='plain') #changing the tick figure from le 6 to millions plt.setp(ax1, xticks= np.arange(0, 680, 30), xticklabels=vac_dates) # plot chart ax1.plot(vaccinated['received_at_least_one_dose'], label= 'Total Vaccinated', c='Red') # axis and legend settings ax1.set_ylabel('population (millions)', size= 14) ax1.set_title('Monthly Vaccinated Numbers', size= 20) plt.xticks(rotation=45) plt.grid() ax1.legend(loc="upper left") ########################################################## # plot daily covid cases ax2 = ax1.twinx() # np.arrange looks at the number of rows plt.setp(ax2, xticks= np.arange(0, 1035, 31), xticklabels=dates) ax2.xaxis.tick_top() ax2.plot(infected_update) plt.xlabel('date', fontsize=14) plt.ylabel('population (thousands)', fontsize=14) plt.grid(False) ax2.legend(['imported','local'], loc="upper right")
输出图表

解决方案
问题核心在于原代码未对数据进行日期筛选,且双轴的xticks使用固定数值范围导致日期错位。以下是修正后的代码及关键说明:
修正后代码
import pandas as pd import numpy as np import matplotlib.pyplot as plt # ---------------------- 数据预处理 ---------------------- # 确保两个数据集的日期列转换为datetime类型(需根据实际列名调整) vaccinated['date'] = pd.to_datetime(vaccinated['date']) infected_update['date'] = pd.to_datetime(infected_update['date']) # 筛选2021年1月1日之后的数据 start_date = '2021-01-01' vaccinated_filtered = vaccinated[vaccinated['date'] >= start_date] infected_filtered = infected_update[infected_update['date'] >= start_date] # ---------------------- 绘图部分 ---------------------- fig, ax1 = plt.subplots(1, figsize=(20,10)) plt.ticklabel_format(style='plain') # 基于筛选后的数据集设置xticks,避免固定索引错位 xticks_step = 30 # 每30天显示一个刻度 xticks_indices = np.arange(0, len(vaccinated_filtered), xticks_step) # 将日期格式化为「月-年」形式 xticks_dates = vaccinated_filtered['date'].iloc[xticks_indices].dt.strftime('%b-%Y') plt.setp(ax1, xticks=xticks_indices, xticklabels=xticks_dates) # 绘制筛选后的疫苗接种数据(红线从2021年1月开始) ax1.plot(vaccinated_filtered['received_at_least_one_dose'], label='Total Vaccinated', c='Red') ax1.set_ylabel('population (millions)', size=14) ax1.set_title('Monthly Vaccinated Numbers (Jan 2021 onwards)', size=20) plt.xticks(rotation=45) plt.grid() ax1.legend(loc="upper left") # 处理双轴的疫情数据,确保日期与左轴对齐 ax2 = ax1.twinx() plt.setp(ax2, xticks=xticks_indices, xticklabels=xticks_dates) ax2.xaxis.tick_top() ax2.plot(infected_filtered) plt.xlabel('date', fontsize=14) plt.ylabel('population (thousands)', fontsize=14) plt.grid(False) ax2.legend(['imported','local'], loc="upper right") plt.tight_layout() plt.show()
关键修正点
- 数据筛选:先将日期列转为datetime类型,筛选出2021年1月之后的数据,确保红线起始时间正确。
- 统一xticks:双轴使用相同的刻度索引和日期标签,避免原代码中两个轴刻度范围不一致导致的日期错位。
- 动态刻度生成:基于筛选后的数据集长度生成刻度,适配新的时间区间。
内容的提问来源于stack exchange,提问作者frank888
相关产品推荐
相关产品推荐

