简体   繁体   English

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

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

I'm plotting an a line plot and an image side by side.我正在绘制一条线 plot 和并排的图像。 Here is my code and the current output:这是我的代码和当前的 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)

电流输出

The image is scaled down and the lineplot is enlarged on the y-axis.图像按比例缩小,线图在 y 轴上放大。 I want both figures to have the same size vertically (y-axis) - I want to have the vertical height of the line plot reduced to have the same size of the image.我希望两个图形在垂直方向(y 轴)上具有相同的大小 - 我希望将 plot 线的垂直高度减小为具有相同大小的图像。

I tried changing the figure size of the subplots and editing the gridspec parameter as mentioned here but that only changes the width of the image, not the height.我尝试更改子图的图形大小并编辑此处提到的 gridspec 参数,但这只会更改图像的宽度,而不是高度。 Any help is appreciated!任何帮助表示赞赏!

One simple solution is to use automatic aspect on the image.一种简单的解决方案是在图像上使用自动纵横比。

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

This will make the shape of your image same as your other plot.这将使您的图像形状与您的其他 plot 相同。

Specifying the overall graph size and adding the subplot will look like this.指定整体图形大小并添加子图将如下所示。

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