3

I want to plot a curve with some measurement data. It is available as an array that contains items of the form [t,b], where t is the parameter that I want to plot and b is a string that describes the status of the measurement equipment. I now want to plot the values of t and have the line colored depending on the value of b. My code so far is

import pylab as pl
measurements = [[0, "a"], [1, "b"], [2, "c"]]
times = pl.arange(0, 3, 1)
values = zip(*measurements)[0]
parameters = zip(*measurements)[1]
pl.plot(times, values)
pl.show()

The line should now have different colors, depending on the values in parameters. How do I do this?

Till B
  • 1,248
  • 2
  • 15
  • 19

2 Answers2

2

The best way to do this is with matplotlib's colormap API.

from matplotlib import pyplot as pl
from matplotlib import cm

pl.scatter(times, values, c = cm.spectral(1.*values/max(values)))

Obviously you'll want to use some other function to get a color from your data. In general though, cm.spectral (or any other colormap) will return a color given a float between zero and one, or an int between 0 and 255.

As a general comment, you might also be better off using numpy arrays rather than trying to zip your data together. It might be easier with more complicated data structures than this example.

import numpy as np
from matplotlib import pyplot as pl
from matplotlib import cm

measurements = np.array([[0, "a"], [1, "b"], [2, "c"]])
times = np.arange(3)
values = np.array(measurements[:,0], dtype=float)
parameters = np.array(measurements[:,1], dtype='S1')

pl.scatter(times, values, c = cm.spectral(values/max(values)))
pl.show()
askewchan
  • 45,161
  • 17
  • 118
  • 134
  • Unfortunately that code does not work (and not only because of the missing bracket) and I also do not find a colormap tutorial that helps me in my case. – Till B Mar 04 '13 at 17:39
  • Sorry, should be `scatter` to allow for color to be a list of colors of the same shape. See edit. – askewchan Mar 04 '13 at 17:41
-6

The easiest way to draw a graph probably would be to use google's Chart API: https://developers.google.com/chart/

This isn't purely python at all, but a resource worth looking at. Hope it helps.

Dave Pedu
  • 1
  • 1
  • Hmm, no, that is unfortunately out of the question. I am bound to use pylab. And the whole thing is embedded into more Python code, so I really doubt that it is the easiest way to interface with Google Chart. – Till B Mar 04 '13 at 17:06