将带有次要y轴的 pandas 条形图的图例放在条形图的前面 [英] Put the legend of pandas bar plot with secondary y axis in front of bars

查看:72
本文介绍了将带有次要y轴的 pandas 条形图的图例放在条形图的前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有辅助y轴的pandas DataFrame,我需要一个条形图,在条形图的前面有图例.目前,图例前面有一组标尺.如果可能的话,我还要将图例放在左下角.任何想法表示赞赏!

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!

我试图设置legend = false并添加一个自定义的图例,但是存在相同的问题.我已经尝试过对列进行重新排序,但是无法在图表上为此清除空格.

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!

推荐答案

您可以自己创建图例.

You can create the legend yourself.

使用颜色循环器将列压缩后,可以使颜色正确.确保在条形图中设置legend=False. loc=3是左下角.

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

这篇关于将带有次要y轴的 pandas 条形图的图例放在条形图的前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆