简体   繁体   English

matplotlib错误栏图-使用自定义颜色图

[英]matplotlib errorbar plot - using a custom colormap

I'm trying to make an errorbar plot with different colors for each point along the x axis. 我正在尝试为x轴上的每个点制作一个具有不同颜色的误差线图。 The errorbar chart itself is coming out fine, but it bombs when I try to use a colormap, so I must be doing it wrong. 错误条形图本身可以很好地显示,但是当我尝试使用颜色图时它会炸弹,因此我必须做错了。 Here's a contrived example of what I'm trying to do: 这是我想要做的一个人为的示例:

import matplotlib.pyplot as plt

colors = ["b","g","c","m","y","k","r","g","c","m","y","k",
          "b","g","c","m","y","k","r","g","c","m","y","k"]

xlabels = ['A','B','8','14']

xval = [0, 1, 2, 3]
yval = [0, 1, 4, 9]
yerr = [0.5, 0.4, 0.6, 0.9]


cmap = dict(zip( xval,colors))

Now after I run this I can go: 现在,运行此命令后,我可以去:

plt.errorbar(xval, yval, yerr=yerr, color='b')

and this gives me the chart shown below (ie, it works. But when I try to do this: 这给了我下面的图表(即,它可以工作。但是当我尝试这样做时:

plt.errorbar(xval, yval, yerr=yerr, color=cmap)

it gives me an error, like " ValueError: to_rgba: Invalid rgba arg "{0: 'b', 1: 'g', 2: 'c', 3: 'm'}" 它给了我一个错误,例如“ ValueError:to_rgba:Invalid rgba arg“ {0:'b',1:'g',2:'c',3:'m'}”

Is it possible to do what I'm tryng to do? 可以做我想做的事吗? Waht I am trying to do is to have each of the 4 points in the errorbar chart have a different color. 我试图做的是让误差条形图中的4个点中的每个点都有不同的颜色。 I wouldn't need the line connecting the points really. 我真的不需要连接这些点的线。 Appreciate any help/advice. 感谢任何帮助/建议。

错误条形图

I already mentioned that you can loop over each particular point/color. 我已经提到过,您可以遍历每个特定的点/颜色。

Another solution is to use a scatter plot within your errorbar plot, like in this question . 另一个解决方案是在您的errorbar图中使用scatter ,就像这个问题一样 The code is below 代码如下

import matplotlib.pyplot as plt

colors = ["b","g","c","m","y","k","r","g","c","m","y","k",
          "b","g","c","m","y","k","r","g","c","m","y","k"]

xlabels = ['A','B','8','14']

xval = [0, 1, 2, 3]
yval = [0, 1, 4, 9]
yerr = [0.5, 0.4, 0.6, 0.9]

plt.scatter(xval, yval, c=colors, s=50, zorder=3)
plt.errorbar(xval, yval, yerr=yerr, zorder=0, fmt="none",
             marker="none")

plt.savefig("scatter_error.png", dpi=300)
plt.show()

With the following result 结果如下

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM