【问题标题】:Plotting Bar and Line charts with Pandas data frame using secondary Y axis and adding the legend together使用辅助 Y 轴使用 Pandas 数据框绘制条形图和折线图并将图例添加在一起
【发布时间】:2015-11-24 12:20:53
【问题描述】:

我使用 Pandas 数据框创建了一个绘图,其中我在主要 Y 轴上有一个条形图,在次要 Y 轴上有一个折线图。X 轴很常见,因此使用了 twinx 方法。

这是我使用的代码

ax = df.plot(x=['TIME'],y =['Column A'],kind='bar',use_index=True,color='g',legend=True)
ax.set_ylabel("Label A")

ax2 = ax.twinx()

ax2.plot(df[['Column B']].values,linestyle='-', marker='o', linewidth=2.0,color ='b')
ax2.set_ylabel("Label B")

这将创建所需的图表,但仅显示主要图例。我尝试将 ax2.plot 线更改为

ax2.plot(df[['Column B']].values,linestyle='-', marker='o', linewidth=2.0,color ='b',legend=True)

但这给了我一个错误,因为“TypeError: There is no line property "legend"” 你们可以看看如何显示属于这两个属性的组合图例。

非常感谢。 莫晨

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以使用legend 方法来处理每个轴的图例,例如

    ax.legend('A', loc=1)
    
    # ....
    
    ax2.legend('B', loc=2)
    

    这是matplotlib中的传奇指南:http://matplotlib.org/users/legend_guide.html

    【讨论】:

    • Joe 感谢您的回复,它可以工作,但是我必须手动传递图例,我可以让它自动获得与标签相同的名称..?
    • 不是通过matplotlib API,但是您已经手动输入了列名,所以我没有看到问题,只需将您要绘制的列定义为变量,然后将其传递给两者,例如col = 'Column B'; ax.plot(df[col].values, ...); ax.legend(col, ...)
    • 你好,当我保存情节时,虽然我为它们选择了不同的位置,但图例会相互堆叠。但是 MATPLOTLIB 图显示了正确的位置。
    • 你是如何保存它们的?也许你应该问一个新问题,因为这是题外话。
    猜你喜欢
    • 2019-05-24
    • 2021-05-04
    • 1970-01-01
    • 2015-09-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多