关于python:在matplotlib的条形图中设置不同的错误条颜色

Setting Different error bar colors in bar plot in matplotlib

在matplotlib Python中设置不同的条形颜色之后

我想更改错误栏的颜色。 经过多次尝试,我想出了一种方法:

1
2
3
4
a = plt.gca()
b = a.bar(range(4), [2]*4, yerr=range(4))
c = a.get_children()[8]
c.set_color(['r','r','b','r'])

有什么更好的办法吗? 当然,a.get_children()[8]根本不是通用解决方案。

enter image description here


如果仅要将它们设置为单一颜色,请使用error_kw kwarg(预期是传递给ax.errorbar的关键字参数的字典)。

另外,您知道,可以将一系列Facecolor直接传递给bar,尽管这不会更改错误栏的颜色。

作为一个简单的例子:

1
2
3
4
5
6
7
8
9
10
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.bar(range(4), [2] * 4, yerr=range(1, 5), alpha=0.5,
       color=['red', 'green', 'blue', 'cyan', 'magenta'],
       error_kw=dict(ecolor='gray', lw=2, capsize=5, capthick=2))
ax.margins(0.05)

plt.show()

enter image description here

但是,如果您希望错误栏为不同的颜色,则需要分别绘制它们或在以后进行修改。

如果使用后一个选项,则实际上不能单独更改标题颜色(请注意,@ falsetru的示例中也未更改)。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
colors = ['red', 'green', 'blue', 'cyan', 'magenta']

container = ax.bar(range(4), [2] * 4, yerr=range(1, 5), alpha=0.5, color=colors,
       error_kw=dict(lw=2, capsize=5, capthick=2))
ax.margins(0.05)

connector, caplines, (vertical_lines,) = container.errorbar.lines
vertical_lines.set_color(colors)

plt.show()

enter image description here

上面答案中的caplines对象是两个Line2D的元组:一行用于所有顶盖,而一行用于所有底盖。在不删除该艺术家并在其位置上创建LineCollection的情况下,无法单独更改其颜色(将它们全部设置为相同的颜色很容易)。

因此,在这种情况下,最好单独绘制误差线。

例如。

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

x, height, error = range(4), [2] * 4, range(1,5)
colors = ['red', 'green', 'blue', 'cyan', 'magenta']

fig, ax = plt.subplots()
ax.bar(x, height, alpha=0.5, color=colors)
ax.margins(0.05)

for pos, y, err, color in zip(x, height, error, colors):
    ax.errorbar(pos + 0.4, y, err, lw=2, capsize=5, capthick=2, color=color)

plt.show()

enter image description here


也不是一个通用的解决方案,而是这里。

1
2
3
4
5
6
7
8
9
10
a = plt.gca()
b = a.bar(range(4), [2]*4, yerr=range(4))
c = b.errorbar.lines[2][b.errorbar.has_xerr] # <----
c.set_color(['r', 'r', 'b', 'r'])


# from matplotlib.collections import LineCollection
# next(i
#      for i, x in enumerate(b.errorbar.lines)
#      if x and any(isinstance(y, LineCollection) for y in x)) == 2