繁体   English   中英

如何使用 matplotlib 使每个轴上具有不同范围的子图具有相同的图形大小?

[英]How to make subplots having different range on each axis have the same figure size using matplotlib?

我正在绘制一条线 plot 和并排的图像。 这是我的代码和当前的 output:

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 轴)上具有相同的大小 - 我希望将 plot 线的垂直高度减小为具有相同大小的图像。

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

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

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

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

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

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM