【问题标题】:How to make subplots having different range on each axis have the same figure size using matplotlib?如何使用 matplotlib 使每个轴上具有不同范围的子图具有相同的图形大小?
【发布时间】:2021-06-09 07:46:24
【问题描述】:

我正在并排绘制线图和图像。这是我的代码和当前输出:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#creating some random data
np.random.seed(1234)
df = pd.DataFrame(
    {'px_last': 100 + np.random.randn(1000).cumsum()},
    index=pd.date_range('2010-01-01', periods=1000, freq='B'),
)

fig, ax = plt.subplots(1,2)

ax[0].plot(df.index, df['px_last'])
#reading the image
url = 'https://raw.githubusercontent.com/kornelski/pngquant/master/test/img/test.png'
im = plt.imread(url)
implot = ax[1].imshow(im)

图像按比例缩小,线图在 y 轴上放大。我希望两个图形在垂直方向(y 轴)上具有相同的大小 - 我希望将线图的垂直高度减小为具有相同的图像大小。

我尝试更改子图的图形大小并编辑here 中提到的 gridspec 参数,但这只会更改图像的宽度,而不是高度。任何帮助表示赞赏!

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    一个简单的解决方案是在图像上使用自动纵横比。

    implot = ax[1].imshow(im, aspect="auto")
    

    这将使您的图像的形状与您的其他情节相同。

    【讨论】:

      【解决方案2】:

      指定整体图形大小并添加子图将如下所示。

      fig = plt.figure(figsize=(10,3))
      ax1 = fig.add_subplot(121)
      ax2 = fig.add_subplot(122)
      
      ax1.plot(df.index, df['px_last'])
      #reading the image
      url = 'https://raw.githubusercontent.com/kornelski/pngquant/master/test/img/test.png'
      im = plt.imread(url)
      implot = ax2.imshow(im)
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        • 2022-01-18
        • 2018-01-12
        • 2019-03-28
        • 1970-01-01
        相关资源
        最近更新 更多