【问题标题】:How to increase the size of only one plot in subplots?如何增加子图中只有一个图的大小?
【发布时间】:2022-10-15 01:53:02
【问题描述】:

如果您有两个子图,如何仅更改第二个图的长度? 将figsize=(7,5) 添加到plt.subplots 会更改两个图的大小,但希望仅更改第二个图的大小。

源代码:https://www.w3schools.com/python/matplotlib_subplot.asp

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x1,y1)

#plot 2: how to make the second plot longer? picturing both plots have the same width, but the 2nd plot being longer 
x2 = np.array([0, 1, 2, 3])
y2 = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x2,y2)
plt.show()

# alternative way to plot

fig, (ax1, ax2) = plt.subplots(1, 2,figsize=(7,5))
ax1.plot(x1,y1)
ax2.plot(x2,y2)
plt.show()

没有错误,但是您如何仅调整第二个图的大小但保持图的位置彼此相邻?谢谢!

【问题讨论】:

  • 您需要 width_ratios 关键字参数(参见 here),例如plt.subplots(2, 1, width_ratios=(1, 2))
  • 谢谢!当我将width_ratios 应用于子图时,我不幸收到错误__init__() got an unexpected keyword argument 'width_ratios'...。你知道那是从哪里来的吗?或者你能举个简单的例子说明在哪里申请width_ratios?非常感谢!
  • width_ratios 是个好建议,但它在 matplotlib.gridspec 模块中可用,而不是 subplots

标签: python numpy matplotlib jupyter subplot


【解决方案1】:

Pylustrator 让我们在制作子图后调整它们并取回会给出该结果的代码。 从源代码获取代码后,在导入下方添加两行 pylustrator 需要,并运行它,在出现的交互式界面中,我拖动右侧绘图的底部轴,然后保存。保存后,在文本编辑器中生成的新版本绘图图形的代码。检查我发现它实际上添加了plt.figure(1).axes[1].set_position([0.547727,0.005,0.352273,0.875]) 行,因此我合并了该行以获得类似于您所描述的内容。

import matplotlib.pyplot as plt
import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)

plt.figure(1).axes[1].set_position([0.547727,0.005,0.352273,0.875])

plt.show()

结果:


如果您想在系统上不安装任何东西的情况下试用 Pylustrator,this markdown text 将指导您完成如何在临时远程计算机上的浏览器中试用它。 (使用主存储库中的按钮启动时出现的问题暂时存在问题,因此现在使用this link 启动会话。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2017-12-11
    • 1970-01-01
    • 2013-02-04
    • 2018-12-12
    • 2013-09-20
    相关资源
    最近更新 更多