![](/img/trans.png)
[英]matplotlib.pyplot - fix only one axis limit, set other to auto
[英]How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot
我想將 y 軸的上限設置為“自動”,但我想保持 y 軸的下限始終為零。 我試過“自動”和“自動范圍”,但這些似乎不起作用。 先感謝您。
這是我的代碼:
import matplotlib.pyplot as plt
def plot(results_plt,title,filename):
############################
# Plot results
# mirror result table such that each parameter forms an own data array
plt.cla()
#print results_plt
XY_results = []
XY_results = zip( *results_plt)
plt.plot(XY_results[0], XY_results[2], marker = ".")
plt.title('%s' % (title) )
plt.xlabel('Input Voltage [V]')
plt.ylabel('Input Current [mA]')
plt.grid(True)
plt.xlim(3.0, 4.2) #***I want to keep these values fixed"
plt.ylim([0, 80]) #****CHANGE**** I want to change '80' to auto, but still keep 0 as the lower limit
plt.savefig(path+filename+'.png')
您可以將left
或right
傳遞給set_xlim
:
plt.gca().set_xlim(left=0)
對於 y 軸,使用bottom
或top
:
plt.gca().set_ylim(bottom=0)
只需為以下限制之一設置xlim
:
plt.xlim(left=0)
如前所述,根據 matplotlib 文檔,可以使用matplotlib.axes.Axes
類的set_xlim
方法設置給定軸ax
的 x 限制。
例如,
>>> ax.set_xlim(left_limit, right_limit)
>>> ax.set_xlim((left_limit, right_limit))
>>> ax.set_xlim(left=left_limit, right=right_limit)
一個限制可以保持不變(例如左限制):
>>> ax.set_xlim((None, right_limit))
>>> ax.set_xlim(None, right_limit)
>>> ax.set_xlim(left=None, right=right_limit)
>>> ax.set_xlim(right=right_limit)
要設置當前軸的 x 限制, matplotlib.pyplot
模塊包含xlim
函數,該函數僅包裝matplotlib.pyplot.gca
和matplotlib.axes.Axes.set_xlim
。
def xlim(*args, **kwargs):
ax = gca()
if not args and not kwargs:
return ax.get_xlim()
ret = ax.set_xlim(*args, **kwargs)
return ret
同樣,對於 y 限制,請使用matplotlib.axes.Axes.set_ylim
或matplotlib.pyplot.ylim
。 關鍵字參數是top
和bottom
。
只需在@silvio 上添加一個點:如果您使用軸來繪制figure, ax1 = plt.subplots(1,2,1)
。 然后ax1.set_xlim(xmin = 0)
也有效!
你也可以這樣做:
ax.set_xlim((None,upper_limit))
ax.set_xlim((lower_limit,None))
如果您想使用 set(),這會很有幫助,它允許您一次設置多個參數:
ax.set(xlim=(None, 3e9), title='my_title', xlabel='my_x_label', ylabel='my_ylabel')
set_xlim
和set_ylim
允許None
值來實現這一點。 但是,您必須在繪制數據后使用這些函數。 如果您不這樣做,它將使用默認的 0 表示左/下和 1 表示上/右。 一旦您設置了限制,它不會在每次繪制新數據時重新計算“自動”限制。
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0, 1, 4, 5], [3, 5, 6, 9])
ax.set_xlim(left=2, right=None)
ax.set_ylim(bottom=None, top=7)
plt.show()
(即,在上面的示例中,如果您在最后執行ax.plot(...)
,則不會產生預期的效果。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.