gpt4 book ai didi

python - 将 pandas 条形图的图例与次要 y 轴放在条形图前面

转载 作者:太空狗 更新时间:2023-10-30 00:08:45 27 4
gpt4 key购买 nike

我有一个带辅助 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()

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

link to image

最佳答案

您可以自己创建图例。

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

关于python - 将 pandas 条形图的图例与次要 y 轴放在条形图前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56876823/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com