rana - 3 months ago 57x

Python Question

I'm trying to make a simple 2d plot from a 3 column data sets e.g. y=f(x) and z=f(x). I want to plot xy and would like to display z using color. For example, the rectangular regions between [x1,x2, min(y), max(y)] ... will be filled by a background color depending on the value of z. I tried to use fill_between but could not associate a colormap with it. I'm new to matplotlib and python. I would very much appreciate your comments/suggestions.

Edit: I don't have an accurate plot but I'll try to explain my query with the help of following figure sample plot

say between x=0.5 to x=1, z=1

x=1.0, to x=1.5, z=2 ....

so I would like to cover x=0.5 to x=1 (min(y) to max(y)] with some color that corresponds to z=1, and between x=1, x=1.5, z=2 and so on.. I want to show this variation using a colormap and to display this colorbar at the right side.

Answer

It sound to me like you should use `contourf`

http://matplotlib.org/examples/pylab_examples/contourf_demo.html

This would take `x`

as some dependant variable, produce `y = y(x)`

and `z = z(x)`

. It seems that your `z`

is not dependant on `y`

but contourf can still handle this.

As a simple example:

```
import pylab as plt
x = plt.linspace(0,2,100)
y = plt.linspace(0,10,100)
z = [[plt.sinc(i) for i in x] for j in y]
CS = plt.contourf(x, y, z, 20, # \[-1, -0.1, 0, 0.1\],
cmap=plt.cm.rainbow)
plt.colorbar(CS)
plt.plot(x,2+plt.sin(y), "--k")
```

The are many variations but hopefully this captures the elements you are looking for

Source (Stackoverflow)

Comments