pandas和matplotlib:将两个地块合并为一个图例项 [英] pandas and matplotlib: Combine two plots into one legend item

查看:142
本文介绍了pandas和matplotlib:将两个地块合并为一个图例项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

from pandas import DataFrame
import matplotlib.pyplot as plt

if __name__ == '__main__':
    lower_bound = [0, 1, 2, 3]
    value = [1, 2, 3, 4]
    upper_bound = [2, 3, 4, 5]
    d = {'Lower bound': lower_bound, 'Value': value, 'Upper bound': upper_bound}
    df = DataFrame(data=d)
    ax = df.plot()
    plt.show()

它将创建以下图:

我想要相同的情节,但是,在图例中,我希望将下界"和上限"组合成一个整体,例如界限".而且,当然,两个边界现在将具有相同的颜色(图例中为边界"给出的任何颜色).

I want the same plot, but, in the legend, I want the "Lower bound" and "Upper bound" combined into one, say, "Bounds". And, of course, the two bounds will now be the same color (whatever color is given on the legend for "Bounds").

推荐答案

似乎是这样的:

from pandas import DataFrame
import matplotlib.pyplot as plt

if __name__ == '__main__':
    lower_bound = [0, 1, 2, 3]
    value = [1, 2, 3, 4]
    upper_bound = [2, 3, 4, 5]
    d = {'Lower bound': lower_bound, 'Value': value, 'Upper bound': upper_bound}
    df = DataFrame(data=d)
    ax = df.plot(color=["Blue", "Blue", "Red"])
    lines, labels = ax.get_legend_handles_labels()
    ax.legend([lines[0], lines[2]], ["Bounds", "Value"])
    plt.show()

我对颜色为何按此顺序的猜测:大熊猫在绘制之前必须对列名称进行排序.您会以为

My guess as to why the colors are in that order: pandas must sort column names before it plots. You'd think it would be

colors = ["Blue", "Red", "Blue"]

但是请注意,下界",上界"和值"是键的字母顺序.

But note that "Lower Bound", "Upper Bound", and "Value" is the alphabetical order of your keys.

注意::这是anaconda 2.7,其行为可能与Python 3不同.

NOTE: This was anaconda 2.7, behavior may be different for Python 3.

这篇关于pandas和matplotlib:将两个地块合并为一个图例项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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