Skip to main content
 首页 » 编程设计

python之如何在我的月度情节中去掉年份(matplotlib)

2025年01月19日9bjzhanghao

我使用 python 的 matplotlib 绘制了一个绘图,它在一个共享的 x 轴上绘制了一个由 1000 个不同的每日值序列组成的数据框。 x 轴代表日期,从 1985 年 1 月 1 日到 1985 年 12 月 31 日,但年份无关紧要,仅用于确保所有年份的数据叠加到同一轴上。当用月轴绘制时,我无法避免在第一个“Jan”刻度下显示 1985。这既丑陋又烦人,因为没有数据代表 1985 年(它们是从合成输入数据生成的计算结果)。

如何去掉第一个 x 轴刻度上的年份指示符?我可以以某种方式为不包含年份的数据框定义日期索引吗?只是 mmm-dd?甚至一些用白框或其他东西来涵盖这一年的技巧也会有所帮助。

用于定义图形的代码如下。我知道这是丑陋的脚本,但它可以满足我的需要......:

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(11,8)) 
 
RSEs.plot(ax=axes[0,0], legend=False, title="Reservoir Elevation") 
TBFs.plot(ax=axes[0,1], legend=False, title="Turbine Flow") 
TSs.plot(ax=axes[1,0], legend=False, title="Total Spill") 
OTs.plot(ax=axes[1,1], legend=False, title="Overtopping Flow") 
l1=RLIMS[LimitCols[1]].plot(ax=axes[0,0], color="k", linestyle=":", legend=False) 
l2=RLIMS[LimitCols[0]].plot(ax=axes[0,0], color="k", linestyle=":", legend=False) 
l3=RLIMS[LimitCols[2]].plot(ax=axes[0,0], color="k", linestyle="--", legend=False) 
l4=RLIMS[LimitCols[3]].plot(ax=axes[0,0], color="k", linestyle="--", legend=False) 
 
#fig.autofmt_xdate() 
axes[1,0].fmt_xdata = mdates.DateFormatter("%m") 
axes[1,1].fmt_xdata = mdates.DateFormatter("%m") 
 
axes[0,0].set_ylabel('Reservoir Elevation (m)', fontsize=14) 
axes[0,1].set_ylabel('Turbine Flow (m$^3$/s)',  fontsize=14) 
axes[1,0].set_ylabel('Gated Spill Release (m$^3$/s)', fontsize=14) 
axes[1,1].set_ylabel('Free Overflow Spill (m$^3$/s)', fontsize=14) 
axes[0,0].annotate('(a)', xy=(0.92, 0.9), xycoords='axes fraction', fontsize=14, horizontalalignment='top', verticalalignment='left') 
axes[0,1].annotate('(b)', xy=(0.92, 0.9), xycoords='axes fraction', fontsize=14, horizontalalignment='top', verticalalignment='left') 
axes[1,0].annotate('(c)', xy=(0.92, 0.9), xycoords='axes fraction', fontsize=14, horizontalalignment='top', verticalalignment='left') 
axes[1,1].annotate('(d)', xy=(0.92, 0.9), xycoords='axes fraction', fontsize=14,  
horizontalalignment='top', verticalalignment='left') 
 
axes[0,1].yaxis.set_label_coords(-0.115,0.5) 
axes[1,0].yaxis.set_label_coords(-0.122,0.5) 

日期定义如下所示,用于定义包含 1000 列不同的、综合驱动的每日数据的数据帧的索引值。

dates=pd.DatetimeIndex(start="1985-01-01", end="1985-12-31", freq="D") 

编辑
以下是数据帧的内容.... rse, tbf, ts 和 ot 是尺寸为 365 x 1000 的简单数组。

Cols=np.arange(1,1001) 
 
RSEs=pd.DataFrame(rse, index=dates, columns=Cols) 
TBFs=pd.DataFrame(tbf, index=dates, columns=Cols) 
TSs=pd.DataFrame(ts, index=dates, columns=Cols) 
OTs=pd.DataFrame(ot, index=dates, columns=Cols) 

请您参考如下方法:

只是mmm-dd?

Best 可以通过 X 轴 DateFormatter( fmt, tz = None ) 调整适当的设置,其中 fmt 将设置 < em>strftime-格式化代码:

"%b-%d" # WARNING: %b produced content is locale-specific, 
        #             so review a code in cases, where international deliveries 
        #             may take place in the future 

axes[i,j].xaxis.set_major_formatter( DateFormatter( '%b-%d' ) )