python - 绘制 ax.twin 图时如何在 matplotlib 中将 x 轴刻度设置为日期

标签 python matplotlib

我的数据是:

enter image description here

我可以使用以下代码绘制 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()

结果是这样的: enter image description here

但我想将日期变量放在 x 轴刻度中,现在是 [0,1,2,3] ,所以我尝试了代码:

ax1.xaxis.set_ticks(df['date'])

但显示错误如下: enter image description here

那么我怎样才能以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/

相关文章:

python - 如何根据其他 2 列聚合 pandas 列的计数

python - 如何使用 matplotlib 索引 n 组 4 列以绘制多个图?

python - 我的 if 语句不断为空列表返回 'None'

python - 当单元格包含列表时, Pandas 适用

python - 从python中的图形中提取点

python - Matplotlib:事后更改颜色图

python - 将 numpy 数组(行形式)转换为图像

python - 如何在python中打开mac osx上的文件

javascript - 如何在 python jupyter notebook 中绘图?

python - 使用 histogram2d python 查找平均 bin 值