【问题标题】:Reverse legend order pandas plot反转图例顺序熊猫图
【发布时间】:2016-05-24 06:12:29
【问题描述】:

我有以下代码来显示堆叠条

handles = df.toPandas().set_index('x').T.plot(kind='bar', stacked=True, figsize=(11,11))
    plt.legend(loc='best', title="Line", fontsize = 'small', framealpha=0)
    plt.ylabel("'" + lineName + "'")
    plt.show()

我想颠倒使用handles=handles[::-1]的图例顺序,但出现错误。

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

DataFrame.plot 接受 legend 参数,可以是 True/False/'reverse'。你要legend='reverse'

【讨论】:

  • 它没有工作:df.toPandas().set_index('Product_Line_Name').T.plot(kind='bar',stacked=True,figsize=(11,11),legend ='reverse') plt.legend(loc='best', title="Line", fontsize = 'small', framealpha=0) plt.ylabel("'" + lineName + "'") plt.show()
  • 第二个图例会覆盖第一个图例。
  • @Goyo 我可以在绘图中添加第二个图例参数吗?或者在传说中说反转它?
【解决方案2】:

这是一个直接使用 matplotlib 作为图例的最小示例。

df = pd.DataFrame({'a': np.random.randn(10) + 1, 'b': np.random.randn(10),
                   'c': np.random.randn(10) - 1}, columns=['a', 'b', 'c'])
ax = df.plot(kind='bar', stacked=True)
handles, labels = ax.get_legend_handles_labels()
ax.legend(reversed(handles), reversed(labels), loc='upper left')  # reverse both handles and labels

(我在上面的图中使用了 plt.style.use('ggplot')。)

另请参阅matplotlib legend guide

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多