带有特定颜色和图例位置的 pandas 条形图? [英] Pandas bar plot with specific colors and legend location?

查看:95
本文介绍了带有特定颜色和图例位置的 pandas 条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一只熊猫DataFrame,我想绘制一个包含图例的条形图.

I have a pandas DataFrame and I want to plot a bar chart that includes a legend.

import pylab as pl
from pandas import *

x = DataFrame({"Alpha": Series({1: 1, 2: 3, 3:2.5}), "Beta": Series({1: 2, 2: 2, 3:3.5})})

如果我直接调用图,那么它将图例放在图的上方:

If I call plot directly, then it puts the legend above the plot:

x.plot(kind="bar")

如果我在绘图中打开图例并稍后尝试添加,则它不会保留与DataFrame中的两列关联的颜色(见下文):

If I turn of the legend in the plot and try to add it later, then it doesn't retain the colors associated with the two columns in the DataFrame (see below):

x.plot(kind="bar", legend=False)
l = pl.legend(('Alpha','Beta'), loc='best')

在熊猫数据框的matplotlib图中包括图例的正确方法是什么?

What's the right way to include a legend in a matplotlib plot from a Pandas DataFrame?

推荐答案

如果要手动添加图例,则必须向子图询问条形图的元素:

If you want to add the legend manually, you have to ask the subplot for the elements of the bar plot:

In [17]: ax = x.plot(kind='bar', legend=False)

In [18]: patches, labels = ax.get_legend_handles_labels()

In [19]: ax.legend(patches, labels, loc='best')
Out[19]: <matplotlib.legend.Legend at 0x10b292ad0>

此外,plt.legend(loc='best')ax.legend(loc='best')应该可以正常使用",因为在绘制图形时已经建立了指向条形图补丁的链接",因此您不必传递轴列表标签.

Also, plt.legend(loc='best') or ax.legend(loc='best') should "just work", because there are already "links" to the bar plot patches set up when the plot is made, so you don't have to pass a list of axis labels.

我不确定您使用的熊猫版本是否返回了子图的句柄(ax = ...),但是我很确定0.7.3可以.您始终可以通过plt.gca()来获得对其的引用.

I'm not sure if the version of pandas you're using returns a handle to the subplot (ax = ...) but I'm fairly certain that 0.7.3 does. You can always get a reference to it with plt.gca().

这篇关于带有特定颜色和图例位置的 pandas 条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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