【问题标题】:Bar plot Matplotlib : Date interval (xaxis) issue with twinx条形图 Matplotlib:日期间隔(xaxis)问题与 twinx
【发布时间】:2021-11-11 04:58:15
【问题描述】:

我不明白为什么我的代码不起作用。我想要一个间隔为 1 的 x 轴。

df['Dates'] = pd.to_datetime(df.Dates)

fig, ax = plt.subplots(figsize=(16, 9))
ax.bar(df['Dates'],
       df['Score'],
       color='blue',
       width=2)
date_form = DateFormatter("%d/%m/%Y")
ax.xaxis.set_major_formatter(date_form)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
ax2=ax.twinx()
ax2.plot(df['Dates'],
       df['Price'],
         color = 'black')
plt.show()

【问题讨论】:

    标签: python pandas dataframe matplotlib pycharm


    【解决方案1】:

    目前,ax 的日期格式只是被ax2.plot 覆盖,因此您应该将日期格式器应用到ax2 而不是axautofmt_xdate 也可用于旋转日期标签:

    df['Dates'] = pd.to_datetime(df['Dates'])
    
    fig, ax = plt.subplots(figsize=(16, 9))
    ax.bar(df['Dates'], df['Score'], color='blue', width=1)
    
    ax2 = ax.twinx()
    ax2.plot(df['Dates'], df['Price'], color='black')
    
    # apply the date formatting to ax2 instead of ax
    date_form = DateFormatter('%d/%m/%Y')
    ax2.xaxis.set_major_formatter(date_form)
    ax2.xaxis.set_major_locator(mdates.DayLocator(interval=1))
    
    # rotate the date labels
    fig.autofmt_xdate(ha='center', rotation=90)
    

    这是带有一些随机数据的输出(以后建议将数据粘贴为文本,这样我们就可以直接复制真实数据):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多