簡體   English   中英

我有一個帶有 2 個軸的圖形,如何使它們在 matplotlib 中的 y 軸具有相同的比例?

[英]I have a figure with 2 axes, how do I make them have the same scale in y axis in matplotlib?

這是代碼。 兩個軸有兩個不同的比例。 (ax1 有負值和正值,而 ax2 只有負值)。 該圖應該是這樣的,即 ax1 在 x 軸頂部有一條線(正點),在 x 軸下有另一條線(帶有負 x 刻度)。 ax2 也一樣。

你可以在這里看到結果圖: 結果圖如下所示

x_ax = list(np.arange(10))
y_ax = list(np.arange(-10,0))
x_ax1 = list(np.arange(10))
y_ax1 = list(np.arange(0,10))
x_ax_p = list(np.arange(10))
y_ax_p = list(np.arange(-30,-20))
x_ax1_p = list(np.arange(10))
y_ax1_p = list(np.arange(-40,-30))



fig = plt.figure(figsize = (10,10))
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax2 = fig.add_axes([0.9,0.1,0.8,0.8])
ax1.spines['left'].set_color('none')
# ax1.spines['right'].set_color('none')
ax1.spines['top'].set_color('none')
# ax1.spines['bottom'].set_position('zero')
# ax2.spines['left'].set_position(('axes', 0))
ax2.spines['right'].set_color('none')
ax2.spines['top'].set_color('none')
# ax2.spines['bottom'].set_position('zero')
#ax1.set_xticks([])
ax1.set_yticks([])
#ax2.set_xticks([])
ax2.set_yticks([])
x_offset= 0.2 # for displaying the values
y_offset= 2 
##################enter code here#########################
ax1.plot(range(len(x_ax)),y_ax,marker='o', label = 'Test_store')
ax1.plot(range(len(x_ax1)),y_ax1,marker='o', label = 'Control_store')

##############################################
ax2.plot(range(len(x_ax_p)),y_ax_p,marker='o', label = 'Test_store')
ax2.plot(range(len(x_ax1_p)),y_ax1_p,marker='o', label = 'Control_store')

for i,j in zip(range(len(x_ax)),y_ax):
    ax1.annotate(round(j,2),xy=(i,j),xytext = (i,j))
for i,j in zip(range(len(x_ax1)),y_ax1):
    ax1.annotate(str(round(j,2)),xy=(i,j),xytext = (i,j))
for i,j in zip(range(len(x_ax_p)),y_ax_p):
    ax2.annotate(str(round(j,2)),xy=(i,j),xytext = (i,j))
for i,j in zip(range(len(x_ax1_p)),y_ax1_p):
    ax2.annotate(str(round(j,2)),xy=(i,j),xytext = (i,j))

ax1.text(8.5, -15, 'Week', ha='right')
ax1.set_ylabel("Sales")
ax1.set_title("Period : "+ per + " "+ "\n" +"Week vs Sales")
ax2.set_title("Period : "+"Pilot Phase"+ "\n"+"Week vs Sales")
ax1.set_xticks(np.arange(len(x_ax)))
ax2.set_xticks(np.arange(len(x_ax)))
ax2.legend()
plt.show()
fig.clear()

要為兩個圖形指定相同的 y 軸限制,您可以使用set_ylim

ymin, ymax = 0, 100  # Change these to whatever values you require
ax1.set_ylim(ymin, ymax)
ax2.set_ylim(ymin, ymax)

您還可以使用 Matplotlib 生成的默認 y 限制的最小值和最大值來動態設置限制,即無需手動指定它們:

ymin = min([ax1.get_ylim()[0], ax2.get_ylim()[0]])
ymax = max([ax1.get_ylim()[1], ax2.get_ylim()[1]])
ax1.set_ylim(ymin, ymax)
ax2.set_ylim(ymin, ymax)

要將 x 軸刻度的垂直位置設置為零,您可以使用以下命令:

ax1.spines['bottom'].set_position('zero')
ax2.spines['bottom'].set_position('zero')

如果您想使用零以外的值,以上是以下的簡寫:

ax1.spines['bottom'].set_position(("data", 0))
ax2.spines['bottom'].set_position(("data", 0))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM