Reputation: 189626
I would like to plot a 3xN matrix to obtain three lines, specifying the colors for each one. I can do this with three separate calls to plot()
:
fig = plt.figure()
theta = np.arange(0,1,1.0/720) * 2 * np.pi
abc = np.cos(np.vstack([theta, theta+2*np.pi/3, theta+4*np.pi/3])).T
ax = fig.add_subplot(1,1,1)
ax.plot(theta,abc[:,0],color='red')
ax.plot(theta,abc[:,1],color='green')
ax.plot(theta,abc[:,2],color='blue')
Is there a way to do the same thing, specifying colors with one call to plot()
?
ax.plot(theta,abc,????)
I've tried
ax.plot(theta,abc,color=['red','green','blue'])
but I get ValueError: could not convert string to float: red
in a callback.
Upvotes: 1
Views: 253
Reputation: 339052
An option is to change the color cycle from which colors are chosen automatically, such that it contains those colors needed for the plot.
ax.set_prop_cycle('color', ["red", "green","blue"])
ax.plot(theta,abc)
This can also be done using rcParams, see e.g. here.
Complete example:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
theta = np.arange(0,1,1.0/720) * 2 * np.pi
abc = np.cos(np.vstack([theta, theta+2*np.pi/3, theta+4*np.pi/3])).T
ax = fig.add_subplot(1,1,1)
ax.set_prop_cycle('color', ["red", "green","blue"])
ax.plot(theta,abc)
plt.show()
Upvotes: 1
Reputation: 40667
As far as I know, that's not possible. According to the documentation the color=
argument must be a single color (or an array of 3-4 floats). Is there a particular reason you need to do only one call?
If it must be a one-liner, you could do the following:
ax.plot(theta,abc[:,0],color='red',theta,abc[:,1],color='green',theta,abc[:,2],color='blue')
which is one line, but does not really save on typing.
Or:
for i,c in enumerate(['red','green','blue']):
ax.plot(theta,abc[:,i],color=c)
EDIT
Actually, I thought of one way to do this.
If you simply call plot(theta, abc[:,:])
, the colors will be cycled through the list of colors in the rcParams axes.prop_cycle
.
Therefore, you could (temporarily) change the color cycle to red,green,blue before calling your plot command.
from cycler import cycler
#save the current color cycler
old = matplotlib.rcParams['axes.prop_cycle']
#set the color cycler to r,g,b
matplotlib.rcParams['axes.prop_cycle'] = cycler(color=['r','g','b'])
fig = plt.figure()
theta = np.arange(0,1,1.0/720) * 2 * np.pi
abc = np.cos(np.vstack([theta, theta+2*np.pi/3, theta+4*np.pi/3])).T
ax = fig.add_subplot(1,1,1)
ax.plot(theta,abc) # <----- single call to `plot` for the 3 lines
#restore original color cycle
matplotlib.rcParams['axes.prop_cycle'] = old
Upvotes: 1