【问题标题】:Put the legend of pandas bar plot with secondary y axis in front of bars将带有次 y 轴的 pandas 条形图的图例放在条形前面
【发布时间】:2019-11-14 12:56:45
【问题描述】:

我有一个带有辅助 y 轴的 pandas DataFrame,我需要一个条形图,条形图前面有图例。目前,一组条形图位于图例前面。如果可能的话,我还想把图例放在左下角。任何想法表示赞赏!

我尝试设置 legend=false 并添加自定义图例,但也存在同样的问题。我已尝试重新排序列,但无法在图表上为此清除空间。

import pandas as pd
import matplotlib.pyplot as plt

df_y = pd.DataFrame([['jade',12,800],['lime',12,801],['leaf',12,802], 
       ['puke',12,800]], columns=['Territory','Cuisines','Restaurants'])
df_y.set_index('Territory', inplace=True)

plt.figure()
ax=df_y.plot(kind='bar', secondary_y=['Restaurants'])
ax.set_ylabel('Cuisines')
ax.right_ax.set_ylabel('Restaurants')
plt.show()

一组条出现在图例的后面,一组出现在图例的前面。下面的链接转到显示问题的图像。谢谢!

【问题讨论】:

    标签: python pandas matplotlib plot jupyter-notebook


    【解决方案1】:

    您可以自己创建图例。

    使用颜色循环器在与列一起压缩时获得正确的颜色。确保在条形图中设置legend=Falseloc=3 是左下角。

    import matplotlib.patches as mpatches
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    df_y.plot(kind='bar', secondary_y=['Restaurants'], legend=False, ax=ax)
    ax.set_ylabel('Cuisines')
    ax.right_ax.set_ylabel('Restaurants')
    
    L = [mpatches.Patch(color=c, label=col) 
         for col,c in zip(df_y.columns, plt.rcParams['axes.prop_cycle'].by_key()['color'])]
    
    plt.legend(handles=L, loc=3)
    plt.show()
    

    【讨论】:

    • 谢谢!我将花一些时间更多地了解这个库以及它是如何生成的。正是我想要的。