首页 > 解决方案 > 如何将图例添加到具有相同颜色的错误栏的图中

问题描述

我想用两个数据集绘制一个图表,其中一个数据集在 y 方向上有误差线。这些应该被标记。如何使第一个图的误差线、线和标签具有相同的颜色?我包括了相应的情节。

import matplotlib.pyplot as plt

a = [0,1,3,5,10]
b = [5,5,2,10,4]
c  = [5,5,1,1,1]
d = [1,1,2,3,4]

plt.plot(a, b, label = "b")
plt.plot(a, c,label ="c")

plt.legend(loc= "upper left")

plt.errorbar(a, b, d)

plt.xlabel("xlab")
plt.ylabel("ylab")
plt.show()

我收到的情节

标签: pythonmatplotlib

解决方案


该类matplotlib.lines.Line2D对于定义自定义图例很有用。

代码

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

x = [0,1,3,5,10]
y1 = [5,5,2,10,4]
y2  = [5,5,1,1,1]
e = [1,1,2,3,4]

# Define colours
c1 = "b"
c2 = "r"

plt.errorbar(x, y1, e, c=c1)
plt.plot(x, y2, c=c2)

plt.legend(
    loc="upper left",
    handles=[
        Line2D([], [], c=c1, label="b"),
        Line2D([], [], c=c2, label="c"),
    ]
)

plt.xlabel("xlab")
plt.ylabel("ylab")
plt.savefig("temp.png")

温度.png

在此处输入图像描述


推荐阅读