【问题标题】:Same scale but different height for subplots子图的比例相同但高度不同
【发布时间】:2015-09-28 08:42:32
【问题描述】:

我很难在 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()

谢谢

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    ar=ax2.get_position().bounds
    
    ar=((ar[0]-ar[2])/(ar[1]-ar[3]))
    
    aspectratio=ar
    

    做的工作:)

    【讨论】:

      【解决方案2】:

      您可以设置set_ylim 以确保ax1ax2 的轴相同,并使用subplot2grid 将两个图布置在网格上:

      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()
      

      则不需要纵横比。这为您提供如下输出:

      【讨论】:

      • 我可以这样做,但是我只想通过改变其高度来显示上部子图的感兴趣区域。
      • 您可以使用subplot2grid 将顶部子图放置在网格上。则不需要纵横比。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多