簡體   English   中英

為多行調用axis.plot()指定matplotlib顏色

[英]Specifying matplotlib colors for a call to axis.plot() with multiple lines

我想繪制一個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: could not convert string to float: red在回調中為ValueError: could not convert string to float: red

據我所知,這是不可能的。 根據文檔color=參數必須是單色(或3-4個浮點數的數組)。 您是否只需要打一個電話就有特殊原因?

如果它必須是單線的,則可以執行以下操作:

ax.plot(theta,abc[:,0],color='red',theta,abc[:,1],color='green',theta,abc[:,2],color='blue')

這是一行,但是並不能真正節省鍵入的時間。

要么:

for i,c in enumerate(['red','green','blue']):
    ax.plot(theta,abc[:,i],color=c)

編輯

實際上,我想到了一種方法。 如果僅調用plot(theta, abc[:,:]) ,顏色將在rcParams axes.prop_cycle中的顏色列表中循環

因此,您可以(暫時)在調用繪圖命令之前將顏色循環更改為紅色,綠色,藍色。

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

一種選擇是更改從中自動選擇顏色的顏色循環,以使其包含繪圖所需的那些顏色。

ax.set_prop_cycle('color', ["red", "green","blue"]) 
ax.plot(theta,abc)

這也可以使用rcParams完成,請參見例如此處

完整的例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM