我想绘制一个 3xN 矩阵以获得三条线,并指定每条线的颜色。我可以通过三个单独的 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')
有没有办法做同样的事情,通过一次调用 plot()
来指定颜色?
ax.plot(theta,abc,????)
我已经尝试过
ax.plot(theta,abc,color=['red','green','blue'])
但我在回调中得到ValueError:无法将字符串转换为float: red
。
最佳答案
一个选项是更改自动选择颜色的颜色循环,使其包含绘图所需的颜色。
ax.set_prop_cycle('color', ["red", "green","blue"])
ax.plot(theta,abc)
这也可以使用 rcParams 来完成,请参见例如here .
完整示例:
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()
关于python - 为多行调用 axis.plot() 指定 matplotlib 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551064/