子图的尺寸相同但高度不同

时间:2015-09-28 08:42:33

标签: python matplotlib

我很难将相同的比例设置为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()

enter image description here 感谢

2 个答案:

答案 0 :(得分:0)

您可以设置set_ylim以确保ax1ax2的轴相同,并使用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()

然后不需要宽高比。这为您提供了如下输出: enter image description here

答案 1 :(得分:0)

ar=ax2.get_position().bounds

ar=((ar[0]-ar[2])/(ar[1]-ar[3]))

aspectratio=ar

完成工作:)