2010-09-23 162 views
211

我需要幫助設置matplotlib上的y軸限制。這是我嘗試的代碼,但沒有成功。在matplotlib中設置y軸限制

import matplotlib.pyplot as plt 

plt.figure(1, figsize = (8.5,11)) 
plt.suptitle('plot title') 
ax = [] 
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1") 
ax.append(aPlot) 
plt.plot(paramValues,plotDataPrice[0], color = '#340B8C', 
    marker = 'o', ms = 5, mfc = '#EB1717') 
plt.xticks(paramValues) 
plt.ylabel('Average Price') 
plt.xlabel('Mark-up') 
plt.grid(True) 
plt.ylim((25,250)) 

隨着我對這個圖中的數據,我得到20和200的y軸的限制。然而,我想這應該限制20和250

+1

如果我在末尾添加'plt.show()'以顯示繪圖,則適用於Matplotlib 1.0.0。你使用的是哪個版本和哪個後端? – 2010-09-23 11:41:25

+9

Matplotlib 0.98.5.2,Python 2.6.2爲我工作。我試過'plt.ylim((25,250))'和'plt.ylim(ymax = 250,ymin = 25)'。我正在使用'Agg'後端。 – 2010-09-23 11:50:34

+1

感謝你們倆。它是否適用於您的PDF後端。 – Curious2learn 2010-09-23 12:26:29

回答

6

。您的代碼適用於我,例如Tamás和Manoj Govindan。看起來你可以嘗試更新Matplotlib。如果你不能更新Matplotlib(例如,如果你沒有足夠的管理權限),也許使用不同的後臺和matplotlib.use()可能會有所幫助。

+0

感謝您的檢查!我正在使用pdf後端('matplotlib.use('PDF')')。我正在使用最新版本的Enthought Python Distribution的版本。你能否看看它是否適用於PDF後端。謝謝! – Curious2learn 2010-09-23 12:25:41

+0

它可以在Mac OS X上與PDF後端一起工作。您確定輸出文件確實使用'plt.savefig()'更新了嗎? – EOL 2010-09-23 13:43:32

+0

我想,我意識到了這個問題。如果我在'plt.subplot'行中取出'aPlot =',它也適用於我。似乎如果將子圖分配給這樣的變量,則必須使用其他一些設置軸限制的方法。真的嗎? – Curious2learn 2010-09-23 13:47:48

89

您的代碼也適用於我。然而,另一種解決方法可以是讓劇情的軸,然後只改變y值:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))

316

試試這個。也適用於子情節。

axes = plt.gca() 
axes.set_xlim([xmin,xmax]) 
axes.set_ylim([ymin,ymax]) 
+34

順便說一句,這是一個愚蠢的縮寫意思是「** g ** et ** ** ** ** ** xes」。 – 2017-05-08 10:57:10

+1

Lenar,優秀。我偶然聽到這個詞,也聽說它起源於matlab。有用的評論。 – Arjee 2017-11-09 19:29:49

4

要添加到@ Hima的答案,如果要修改當前的x或y限制,您可以使用以下內容。

import numpy as np # you probably alredy do this so no extra overhead 
fig, axes = plt.subplot() 
axes.plot(data[:,0], data[:,1]) 
xlim = axes.get_xlim() 
# example of how to zoomout by a factor of 0.1 
factor = 0.1 
new_xlim = (xlim[0] + xlim[1])/2 + np.array((-0.5, 0.5)) * (xlim[1] - xlim[0]) * (1 + factor) 
axes.set_xlim(new_xlim) 

我覺得這個特別有用,當我想縮小或放大一點從默認繪圖設置。