【问题标题】:pandas plotting barplot with secondary y-axis: misaligned on the x-axispandas 绘制带有辅助 y 轴的条形图:在 x 轴上未对齐
【发布时间】:2019-09-05 21:49:35
【问题描述】:

我正在尝试使用 pandas DataFrame 绘制带有辅助 y 轴的条形图。但是,返回的图形在 x 轴上未对齐,如下所示

换句话说,似乎黑色曲线的 x=1 对应于条形图的 x=2。有一个简单的解决方法吗?数据框具有以下值:

生成图的代码如下:

values = np.array([[ 5.8,  3.5,  0.7, 32.2],
       [ 4.8,  4.7,  0.5, 23.5],
       [ 4.8,  4.7,  0.5, 23.1],
       [ 4.6,  5.1,  0.3, 23.6],
       [ 4.4,  5.2,  0.5, 22.1]])

pdata = pd.DataFrame(values,index=[1,2,3,4,5],columns=['a1', 'a2', 'a3', 'pie'])

fig,ax = plt.subplots(figsize=(5,3))
axp = ax.twinx()

pdata[['a1','a2','a3']].plot(ax=ax,kind='bar',stacked=True,rot=0)
pdata['pie'].plot(ax=axp,color='k',rot=0)
axp.set_ylim([0,100])
ax.set_ylim([0,10])

ax.legend(loc=2)  
axp.legend(loc=1)
ax.set_ylabel('value')
axp.set_ylabel('pie')

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    df.plot(kind='bar') 根据range(len(df)) 绘制条形图,并用df.index 标记刻度。由于您的索引是1,2,3,4,5,您会看到线图发生了移动。

    一种解决方法是手动绘制pie

    fig,ax = plt.subplots(figsize=(5,3))
    axp = ax.twinx()
    
    pdata[['a1','a2','a3']].plot(ax=ax,kind='bar',stacked=True,rot=0)
    
    # note the difference
    axp.plot(range(len(pdata)), pdata['pie'], color='k')
    
    axp.set_ylim([0,100])
    ax.set_ylim([0,10])
    
    ax.legend(loc=2)  
    axp.legend(loc=1)
    ax.set_ylabel('value')
    axp.set_ylabel('pie')
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2017-08-06
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多