2012-02-14 121 views
3

我想在matplotlib中繪製可變數量的行,其中X,Y數據和顏色存儲在numpy數組中,如下所示。有沒有辦法將顏色數組傳遞到繪圖函數中,所以我不必採取額外的步驟來爲每條線單獨分配顏色?我是否應該將RGB顏色數組轉換爲另一種顏色格式才能正常工作,如HSV或其他顏色格式?Matplotlib:爲行分配顏色

import numpy as np 
X = np.arange(1990, 1994) 
Y = [[ 1.50615936e+08 5.88252480e+07 2.60363587e+08] 
    [ 1.53193798e+08 5.91663430e+07 2.63123995e+08] 
    [ 1.55704596e+08 5.94899260e+07 2.65840188e+08] 
    [ 1.58175186e+08 5.97843680e+07 2.68559452e+08]] 
colors = [(0.99609375, 0.3984375, 0.3984375) (0.796875, 0.0, 0.99609375) 
      (0.59765625, 0.99609375, 0.0)] 
#current way 
ax.plot(X, Y) 
[ax.lines[i].set_color(color) for i, color in enumerate(colors)] 
#way I feel it can be done, but doesn't work currently 
ax.plot(X, Y, color=colors) 
plt.show() 

任何幫助,非常感謝。

回答

5

我想你想使用Axes方法set_color_cycle。您可以想象,它會設置在默認情況下分配顏色時循環顯示的顏色列表,即,當沒有顏色關鍵字提供給plot調用時。這裏是你的榜樣的擴展版本:

import matplotlib.pyplot as plt 
import numpy as np 

X = np.arange(1990, 1994) 
Y = [[ 1.50615936e+08, 5.88252480e+07, 2.60363587e+08], 
    [ 1.53193798e+08, 5.91663430e+07, 2.63123995e+08], 
    [ 1.55704596e+08, 5.94899260e+07, 2.65840188e+08], 
    [ 1.58175186e+08, 5.97843680e+07, 2.68559452e+08]] 
colors = [(0.99609375, 0.3984375, 0.3984375), 
      (0.796875, 0.0, 0.99609375), 
      (0.59765625, 0.99609375, 0.0)] 

fig = plt.figure() 
ax1 = fig.add_subplot(211) 
ax1.set_title('old way') 
ax1.plot(X, Y) 
[ax1.lines[i].set_color(color) for i, color in enumerate(colors)] 

ax2 = fig.add_subplot(212) 
ax2.set_title('new way') 
ax2.set_color_cycle(colors) 
ax2.plot(X, Y) 

fig.savefig('manycolors.py') 
plt.show() 

這將導致兩個次要情節與相同顏色的線:

enter image description here

+2

感謝您指向ax.set_color_cycle()的方向。從那裏我發現:mpl.rcParams ['axes.color_cycle'] = self.colors這正是我想要的,因爲我正在繪製多個子圖並需要相同的顏色。 – hotshotiguana 2012-02-14 21:29:25

0

還有比建議由「新路」 @Yann,自Matplotlib版本1.5。使用(depricated)代替set_color_cycle,應該使用set_prop_cycle。在這裏,你重做他的例子。我也建議你使用Seaborn,它有很多預先調好的調色板,你可以選擇顏色的數量。調色板顏色基於Colorbrewer,這是一款用於選擇優質彩色地圖的工具。 所以這是我的@Yann代碼版本:

import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns 

X = np.arange(1990, 1994) 
Y = [[ 1.50615936e+08, 5.88252480e+07, 2.60363587e+08], 
    [ 1.53193798e+08, 5.91663430e+07, 2.63123995e+08], 
    [ 1.55704596e+08, 5.94899260e+07, 2.65840188e+08], 
    [ 1.58175186e+08, 5.97843680e+07, 2.68559452e+08]] 

colors = sns.color_palette("hls", len(Y[0])) 

fig = plt.figure() 
ax1 = fig.add_subplot(211) 
ax1.set_title('old way') 
ax1.plot(X, Y) 
[ax1.lines[i].set_color(color) for i, color in enumerate(colors)] 

ax2 = fig.add_subplot(212) 
ax2.set_title('new way') 
ax2.set_prop_cycle('color', colors) 
ax2.plot(X, Y) 

plt.show()