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

半腔热情 提交于 2020-07-08 09:02:41

问题


I have a pandas DataFrame with a secondary y axis and I need a bar plot with the legend in front of the bars. 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. 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!

link to image


回答1:


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. loc=3 is the lower left.

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



来源:https://stackoverflow.com/questions/56876823/put-the-legend-of-pandas-bar-plot-with-secondary-y-axis-in-front-of-bars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!