Matplotlib AxesGrid对于具有不同范围的图形来说是相等的可视大小

2024-03-19 11:48:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一个图形来绘制多个函数。图以2x2矩阵排列。function1和function2共享一个公共y轴,function1和function3共享一个公共x轴。我不想在这些情节之间留出空间。我希望所有的情节占据我屏幕上相同的空间,不管它们的范围。

下面的代码几乎可以满足我的要求,但它的规模并不好。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

x = np.linspace(-1,1,1000)
y1 = x
y2 = 0.1*x**2
y3 = x**3

fig = plt.figure()
grid = AxesGrid(fig, 111, nrows_ncols=(2,2), axes_pad=0.0, share_all=True)
grid[0].plot(x,y1)                                              
grid[2].plot(x,y2)
grid[1].plot(x,y3)

fig.tight_layout()
plt.show()

问题是函数3看起来非常平坦,并且没有很好地使用空间。如果我选择^{{cd1>},那么这些图的大小就不同了。

我想要的是类似于^{{cd2>}的绘图,但函数3的y轴在范围内(0,0.1)。函数1和函数2的y轴应保持(-1,1)如何实现?


Tags: 函数importplotasnpfig空间plt
1条回答
网友
1楼 · 发布于 2024-03-19 11:48:44

就我所理解的需求而言,似乎没有必要使用AxesGrid。使用normalplt.subplots,可以得到以下结果,这似乎是我们想要的结果

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1,1,1000)
y1 = x
y2 = 0.1*x**2
y3 = x**3

fig, grid = plt.subplots(2,2,sharex="col", sharey="row")
fig.subplots_adjust(wspace=0, hspace=0)
grid[0,0].plot(x,y1)                                              
grid[1,0].plot(x,y2)
grid[0,1].plot(x,y3)

plt.show()

enter image description here

相关问题 更多 >