我的数据是:
我可以使用以下代码绘制 ax.twinx 条形图和线图:
df = pd.DataFrame({'a': [350, 200, 150, 475],'b': [43, 3, 27, 10],'date':pd.date_range('2018-01-01',periods=4)},columns=['date','a','b'])
fig, ax1 = plt.subplots(figsize=(15, 10))
ax2=ax1.twinx()
df['b'].plot(kind='bar', color='y', ax=ax1)
df['a'].plot(kind='line', marker='d', ax=ax2)
ax2.yaxis.tick_right()
ax1.yaxis.tick_left()
ax1.legend(loc=0)
ax2.legend(loc=2)
plt.show()
但我想将日期变量放在 x 轴刻度中,现在是 [0,1,2,3] ,所以我尝试了代码:
ax1.xaxis.set_ticks(df['date'])
那么我怎样才能以x个刻度显示日期呢?
最佳答案
将 ax1.xaxis.set_ticks(df['date'])
替换为:
ax1.set_xticklabels(df['date'])
要使用不同的日期格式,您可以使用此行更改日期列:
df['date'] = df['date'].dt.strftime('%d/%m/%Y')
关于python - 绘制 ax.twin 图时如何在 matplotlib 中将 x 轴刻度设置为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51742072/