2010-08-29 60 views
15

matplotlib中,線條自動繪製顏色循環。這兩條線圖會有不同的顏色。如何讓條形圖自動循環使用不同的顏色?

axes.plot(x1, y) 
axes.plot(x2, y) 

但是,條形圖並沒有。這兩個數據系列都會有藍條。

axes.bar(x1, y) 
axes.bar(x2, y) 

如何讓條形圖在預定義的顏色範圍內自動循環?

回答

4

可選: 要得到完全控制你的人物風格使用現有mplstyle作爲模板: https://github.com/matplotlib/matplotlib/tree/master/lib/matplotlib/mpl-data/stylelib

調整參數:axes.prop_cycle:循環儀( '顏色',[。 ...])

負荷你的風格:

from matplotlib import style 
style.use ('PATH TO YOUR MPL STYLE') 

您可以通過您或默認樣式顏色週期幾乎任何方式週期你想要的:

#!/usr/bin/python 
import matplotlib.pyplot as plt 

#data 
x=[1,2,4] 
y=[11,12,8] 
prop_iter = iter(plt.rcParams['axes.prop_cycle']) 

for i in range(0,len(x)): 
    plt.bar(x[i],y[i],color=next(prop_iter)['color']) 

plt.show() 

plt.rcParams [「axes.prop_cycle」]抓住所有的週期,所以你需要使用的關鍵在於選擇正確的循環儀['顏色']。

可以刪除迭代器創建和使用列表理解和zip創建一個內襯:

#!/usr/bin/python 
import matplotlib.pyplot as plt 

x=[1,2,4] 
y=[11,12,8] 
prop = plt.rcParams['axes.prop_cycle'] 
[plt.bar(param[0],param[1],color=param[2]['color']) for param in zip(x,y,prop)] 
plt.show() 

enter image description here

3

從文檔在http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar

酒吧地塊自動不循環顏色,但你可以直接通過將顏色屬性中的顏色。 像這樣:

colors = ['red', 'blue', 'green'] 
i = -1 
def getCycledColor(): 
    global i, colors 
    if i < len(colors) -1 
     i = i + 1 
     return colors[i] 
    else: 
     i = -1 
axes.bar(x1,y,facecolor=getCycledColor()) 
axes.bar(x2,y,facecolor=getCycledColor()) 

的顏色可以從預定義的列表中選擇並循環。

+0

剛剛產生兩個欄的地塊,一個紅色的所有酒吧和一個藍色的所有酒吧(因爲調用'axes().bar(..)'時只調用一次'getCycledColor()') – 2012-02-23 13:18:53

24

請問這句話是否適合你?

#!/usr/bin/python 
from matplotlib import cm 
import matplotlib.pyplot as plt 

#data 
x=[1,2,4] 
y=[11,12,8] 

for i in range(0,len(x)): 
    plt.bar(x[i],y[i],color=cm.jet(1.*i/len(x))) 

plt.show() 

更多關於colormaps

編輯:見this example關於如何循環在一組預定義的顏色。