我想在一個圖中繪制多個函式,但是如果繪制的一個函式的值比其他函式高/小得多,我想防止軸被擴展。在下面的代碼中,引數alpha實際上是隨機的(這里我將其固定為alpha = 2),并且可能會得到非常高的值,這會打亂我的繪圖。基本上我想做的是,我想繪制一個函式,然后根據它的xlimand凍結軸,然后如果恰好很大ylim,則添加剩余的圖而不擴展軸。alpha我怎樣才能做到這一點?
這個橙色圖擴展了軸,使得其他圖不再可解釋。我希望橙色圖在 y 方向上過沖,如下所示:
但無需ylim手動設定。
uj5u.com熱心網友回復:
繪制參考后,在您的案例 data1 中,您可以使用get_ylim()單獨的變數檢索定義的 y 軸限制,a并b在繪制剩余曲線后相應地重新縮放您的軸set_ylim:
這樣可以確保軸始終根據參考進行縮放,即使 y 軸的下限非常低或為零,它也能正常作業。
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0,4*np.pi)
data1 = np.sin(0.5*x)
alpha = 2
data2 = alpha*np.sin(x)
data3 = np.sin(x)
data4 = np.sin(x)
data5 = np.cos(x)
fig = plt.figure(constrained_layout=True, figsize=(10, 4))
subfigs = fig.subfigures(1, 2, wspace=0.07)
axsLeft = subfigs[0].subplots(1, 1)
# reference axis
axsLeft.plot(x,data1)
a,b = axsLeft.get_ylim()
axsLeft.plot(x,data2) #final prediction
axsLeft.plot(x,data3,'--k',linewidth=2.5)
axsLeft.set_xlabel("x")
# set limit according to reference
axsLeft.set_ylim((a,b))
axsRight = subfigs[1].subplots(2, 1, sharex=True)
axsRight[0].plot(data4)
axsRight[1].plot(data5)
axsRight[1].set_xlabel('x')
fig.show()
uj5u.com熱心網友回復:
如果要調整y軸為data1的最大值和最小值,使用下面的代碼。(0.05 是填充。)
axsLeft.set_ylim(np.min(data1) - 0.05, np.max(data1) 0.05)
如果您希望 alpha 值也根據 data1 變化,您可以通過從 np.max() 和 np.min() 中減去 alpha 值來獲得該值。以下是您上傳的代碼的修改版本。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,4*np.pi)
data1 = np.sin(0.5*x)
alpha = np.max(data1) - np.min(data1) # change 1
data2 = alpha*np.sin(x)
data3 = np.sin(x)
data4 = np.sin(x)
data5 = np.cos(x)
fig = plt.figure(constrained_layout=True, figsize=(10, 4))
subfigs = fig.subfigures(1, 2, wspace=0.07)
axsLeft = subfigs[0].subplots(1, 1)
axsLeft.plot(x,data1)
axsLeft.plot(x,data2) #final prediction
axsLeft.plot(x,data3,'--k',linewidth=2.5)
axsLeft.set_xlabel("x")
axsRight = subfigs[1].subplots(2, 1, sharex=True)
axsRight[0].plot(data4)
axsRight[1].plot(data5)
axsLeft.set_ylim(-alpha / 2 - 0.05, alpha / 2 0.05) # change 2
axsRight[1].set_xlabel('x')
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461703.html
標籤:Python matplotlib 阴谋 轴
上一篇:Python的默認調色板
