简体   繁体   English

将大熊猫条形图的图例与次要y轴放在条形图前面

[英]Put the legend of pandas bar plot with secondary y axis in front of bars

I have a pandas DataFrame with a secondary y axis and I need a bar plot with the legend in front of the bars. 我有一个带有辅助y轴的pandas DataFrame,我需要一个条形图,条形图前面有图例。 Currently, one set of bars is in front of the legend. 目前,一组条形图位于图例的前面。 If possible, I would also like to place the legend in the lower-left corner. 如果可能的话,我还想将图例放在左下角。 Any ideas appreciated! 任何想法赞赏!

I have attempted to set the legend=false and add a custom legend, but it has the same issue. 我试图设置legend = false并添加自定义图例,但它有同样的问题。 I've tried reordering the columns but there's no way to clear a space for this on the chart. 我已经尝试重新排序列,但是没有办法在图表上为此清除空间。

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()

One set of bars appears behind the legend, and one set appears in front of the legend. 图例后面会出现一组条形图,并且图例前面会出现一组条形图。 The link below goes to an image showing the problem. 下面的链接转到显示问题的图像。 Thank you! 谢谢!

链接到图像

You can create the legend yourself. 您可以自己创建图例。

Use the color cycler to get the colors correct when zipped with the columns. 使用颜色循环器在使用列压缩时可以正确显示颜色。 Make sure to set legend=False in the barplot. 确保在条形图中设置legend=False loc=3 is the lower left. loc=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()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM