2009-12-30 151 views
33

有沒有辦法在matplotlib中更改座標軸的顏色(不是嘀嗒聲)?我一直在瀏覽Axes,Axis和Artist的文檔,但沒有運氣; matplotlib畫廊也沒有提示。 有什麼想法?Matplotlib:更改軸的顏色

回答

61

當使用數字,你可以很容易地改變與脊柱顏色:

ax.spines['bottom'].set_color('#dddddd') 
ax.spines['top'].set_color('#dddddd') 
ax.spines['right'].set_color('red') 
ax.spines['left'].set_color('red') 

使用以下方法來改變只蜱:

ax.tick_params(axis='x', colors='red') 
ax.tick_params(axis='y', colors='red') 

而下面只改變標籤:

ax.yaxis.label.set_color('red') 
ax.xaxis.label.set_color('red') 

最後標題:

ax.title.set_color('red') 
+3

優秀的答案,謝謝!給其他人一個註釋:''ax.tick_params(axis ='x',colors ='red',which ='both')'' - which =「both」同時改變主要和次要的刻度顏色。 – kinverarity 2015-03-10 10:53:24

+0

'ax.tick_params(axis ='x',colors ='red')'似乎改變了勾號和標籤的顏色... – Jonathan 2016-02-16 17:00:30

+0

是否可以使用'ax.yaxis.label.set_color('灰色')'這樣一種方式,只有從'y1'到'y2'的嘀嗒聲改變他們的顏色,而其他的仍然沒有改變? – FaCoffee 2016-03-31 14:27:20

16

爲了記錄在案,我這是怎麼設法使其工作:

fig = pylab.figure() 
ax = fig.add_subplot(1, 1, 1) 
for child in ax.get_children(): 
    if isinstance(child, matplotlib.spines.Spine): 
     child.set_color('#dddddd') 
+0

+1,比使用全局rc好多了。 – Mark 2010-01-01 19:15:21

+0

感謝您的這一點,希望matplotlib將增加一個更簡單的方法來實現這一點。 – jhanifen 2010-10-13 17:07:13

7

您可以通過調整默認的控制設定做。

import matplotlib 
from matplotlib import pyplot as plt 

matplotlib.rc('axes',edgecolor='r') 
plt.plot([0, 1], [0, 1]) 
plt.savefig('test.png') 
+0

Matplotlib還有一個[上下文管理器](http://matplotlib.org/users/style_sheets.html#temporary-styling),它允許臨時更改rc參數http://stackoverflow.com/a/41527038/2166823 – 2017-01-07 22:08:33