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

JAM*_*AGE 6 python plot matplotlib pandas jupyter-notebook

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()
Run Code Online (Sandbox Code Playgroud)

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

链接到图片

ALo*_*llz 5

您可以自己创建图例。

使用颜色循环器在列压缩时获得正确的颜色。确保legend=False在条形图中设置。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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明