tave
tave

Reputation: 43

Python Matplotlib: plot with 2-dimensional arguments : how to specify options?

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)

Upvotes: 4

Views: 664

Answers (3)

unutbu
unutbu

Reputation: 879083

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

Upvotes: 5

debianplebian
debianplebian

Reputation: 92

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

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

Upvotes: 1

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58865

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] )

Upvotes: 1

Related Questions