0

I'm trying to make an errorbar plot with different colors for each point along the x axis. 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 (i.e., 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'}"

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. I wouldn't need the line connecting the points really. Appreciate any help/advice.

errorbar chart

Charlie_M
  • 1,281
  • 2
  • 16
  • 20
  • What about a loop where you change the color for every point? – nicoguaro Oct 10 '14 at 03:06
  • It is true I could do it that way, and I did consider that but was hoping to be able to just pass the thing in its entirely to matplotlib and just have matplotlib make it work. I dunno... maybe I'm getting carried away with pythonic aesthics and should jsut do the loop after all ;~) . If you look at what I've done in the example you'd say well that whole thing is clunky anyway, but it's done more elegantly in the actual program. – Charlie_M Oct 10 '14 at 17:25
  • Ok, I will write an answer then... – nicoguaro Oct 10 '14 at 17:53

1 Answers1

3

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. 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

enter image description here

Community
  • 1
  • 1
nicoguaro
  • 3,629
  • 1
  • 32
  • 57