我很难将相同的比例设置为matplotlib中两个子图的y轴。 我可以手动接近这一点。但是,是否可以选择对两个子图采用相同的比例?
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
x=np.array([0,1,2,4])/4.
y1=[0.5,0.5,1.0,1.5]
y2=[0,1,2,4]
fig=plt.figure(figsize=(8,8.5))
ax1=plt.subplot(2,1,1)
plt.plot(x,y1)
plt.yticks([0.5,1,1.5])
plt.grid()
ax2=plt.subplot(2,1,2)
plt.plot(x,y2)
plt.yticks([0.5,1,1.5])
plt.grid()
plt.tight_layout()
ratio1=(ax1.get_xlim()[1]-ax1.get_xlim()[0])/(ax1.get_ylim()[1]-ax1.get_ylim()[0])
ratio2=(ax2.get_xlim()[1]-ax2.get_xlim()[0])/(ax2.get_ylim()[1]-ax2.get_ylim()[0])
aspectratio=0.5
ratio_default= ratio2*aspectratio
ax1.set_aspect(ratio_default)
plt.savefig('demo.png')
plt.show()
答案 0 :(得分:0)
您可以设置set_ylim
以确保ax1
和ax2
的轴相同,并使用subplot2grid
将两个图放在网格形式上:< / p>
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
x = np.array([0,1,2,4])/4.
y1 = [0.5,0.5,1.0,1.5]
y2 = [0,1,2,4]
fig = plt.figure(figsize = (8,8.5))
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3, rowspan=1)
plt.plot(x,y1)
plt.yticks([0.5,1,1.5])
ax1.set_ylim([0, 1.5])
plt.grid()
ax2 = plt.subplot2grid((3,3), (1,0), colspan=3, rowspan=2)
plt.plot(x,y2)
plt.yticks([0.5,1,1.5])
ax2.set_ylim([0, 1.5])
plt.grid()
plt.tight_layout()
ratio1 = (ax1.get_xlim()[1]-ax1.get_xlim()[0])/(ax1.get_ylim()[1]-ax1.get_ylim()[0])
ratio2 = (ax2.get_xlim()[1]-ax2.get_xlim()[0])/(ax2.get_ylim()[1]-ax2.get_ylim()[0])
plt.savefig('demo.png')
plt.show()
答案 1 :(得分:0)
ar=ax2.get_position().bounds
ar=((ar[0]-ar[2])/(ar[1]-ar[3]))
aspectratio=ar
完成工作:)