4

I am plotting several curves as follow:

import numpy as np
import matplotlib.pyplot as plt

plt.plot(x, y)

where x and y are 2-dimensional (say N x 2 for the sake of this example).

Now I would like to set the colour of each of these curves independently. I tried things like:

plot(x, y, color= colorArray)

with e.g. colorArray= ['red', 'black'], but to no avail. Same thing for the other options (linestyle, marker, etc.).

I am aware this could be done with a a for loop. However since this plot command accepts multi-dimensional x/y I thought it should be possible to also specify the plotting options this way.

Is it possible? What's the correct way to do this? (everything I found when searching was effectively using a loop)

tave
  • 43
  • 3
  • possible duplicate of [How to get different lines for different plots in a single figure?](http://stackoverflow.com/questions/4805048/how-to-get-different-lines-for-different-plots-in-a-single-figure) – tacaswell Jun 18 '13 at 20:45
  • I think it's different. The answer in the other post relies on a `for` loop - as basically all the answers I could find on this subject.As mentioned I am aware of this possibility, my question was whether it was possible to achieve control on the display options (color, linestyle, markers, etc.) in a way that is consistent with the use of 2-dimensional data - ie without using a loop. Maybe I wasn't clear enough. – tave Jun 19 '13 at 11:42

3 Answers3

5

You could use ax.set_color_cycle:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2013)
N = 10
x, y = np.random.random((2,N,2))
x.cumsum(axis=0, out=x)
y.cumsum(axis=0, out=y)
fig, ax = plt.subplots()
colors = ['red', 'black']
ax.set_color_cycle(colors)
ax.plot(x,y)
plt.show()

yields enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thanks, this is working. How would you set the other plotting options (marker, linestyle, etc.) for each curve though? – tave Jun 18 '13 at 15:01
  • 3
    There does not seem to be a similar way to cycle through markers or linestyles. I think you are going to need to [use a `for-loop`](http://stackoverflow.com/q/7799156/190597). – unutbu Jun 18 '13 at 16:58
  • OK, thanks. Probably simpler indeed to use a `for` loop then. – tave Jun 19 '13 at 10:10
1

I would plot in the way you are doing, then doing a for loop changing the colors accordingly to your colorArray:

plt.plot(x,y)
for i, line in enumerate(plt.gca().lines):
    line.set_color( colorArray[i] )
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
1

I usually pass one dimensional arrays when doing this, like so :

plot(x[0], y[0], 'red', x[1], y[1], 'black')