把Pandas酒吧的传说与次要的y轴在酒吧前面

2024-09-27 04:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧与一个次要的y轴,我需要一个条形图的图例前面的酒吧。目前,一组酒吧是在前面的传说。如果可能的话,我还想把图例放在左下角。有什么好主意吗!在

我试图设置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()

图例后面显示一组条形图,图例前面显示一组条形图。下面的链接指向显示问题的图像。谢谢您!在

link to image


Tags: 数据importdfaspltax酒吧pd
1条回答
网友
1楼 · 发布于 2024-09-27 04:24:29

你可以自己创造传奇。在

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

enter image description here

相关问题 更多 >

    热门问题