Python绘图-在子图中绘制子图

时间:2020-07-27 11:04:24

标签: python matplotlib seaborn

我想绘制一个表示随变量变化的图形。示例图如下所示。 Sample Figure

这个想法是在子图中绘制子图。注意这与使用具有预定义行数和列数的子图来绘制图不同,即matplotlib.pyplot.subplots(nrows = 2,ncols = 2)

我可以使用matplotlib / seaborn绘制此类数字吗?

2 个答案:

答案 0 :(得分:1)

我绘制了框架并将轴放置在框架内,所有操作均基于编号。子图/框架的数量框架网格的行和列以及不同元素的物理尺寸。

我想大多数代码都是自解释性的,除了我们将轴放置在精确位置的那部分是从Demo Fixed Size Axes窃取的,如果您发现需要说明的地方,请询问

import matplotlib
from mpl_toolkits.axes_grid1 import Divider, Size
from mpl_toolkits.axes_grid1.mpl_axes import Axes
import matplotlib.pyplot as plt
import numpy as np
from itertools import product

mm = lambda d: d/25.4

nplots = 2
wp, hp = mm(40), mm(28)
dxp, dyp = mm(16), mm(12)

nrows, ncols = 3, 2
wf, hf = nplots*(wp+dxp), hp+dyp
dxf, dyf = mm(10), mm(8)

xcorners, ycorners = (np.arange(dxf/2,ncols*(wf+dxf),wf+dxf),
                      np.arange(dyf/2,nrows*(hf+dyf),hf+dyf))

# plus 10 mm for suptitle
fig = plt.figure(figsize=(ncols*(wf+dxf), nrows*(hf+dyf)+mm(10))) 

rect = lambda xy: plt.Rectangle(xy, wf, hf,
                                transform=fig.dpi_scale_trans,
                                figure=fig,
                                edgecolor='k', facecolor='none')
fig.patches.extend([rect(xy) for xy in product(xcorners, ycorners)])

t = np.linspace(0,3.14,315); s = np.sin(t)

for nframe, (y, x) in enumerate(product(ycorners, xcorners), 1):
    for n in range(nplots):
        divider = Divider(fig, (0.0, 0.0, 1., 1.),
                          [Size.Fixed(x+0.7*dxp+n*(wp+dxp)), Size.Fixed(wp)],
                          [Size.Fixed(y+0.7*dyp           ), Size.Fixed(hp)],
                          aspect=False)
        ax = Axes(fig, divider.get_position())
        ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
        ax.plot(t, s)
        fig.add_axes(ax)
        fig.text(x, y, 'Frame %d'%nframe, transform=fig.dpi_scale_trans)

figsize = fig.get_size_inches()
width = figsize[0]*25.4 # mm
fig.suptitle('Original figure width is %.2f mm - everything is scaled'%width)
fig.savefig('pippo.png', dpi=118, facecolor='#f8f8f0')

enter image description here

答案 1 :(得分:-2)

您将需要使用Matplotlib绘制这些图

您可以按照以下示例使用图形创建自己的图形:

import matplotlib.pyplot as plt

plt.subplot(1, 2, 1)  # Args ( Lines, Columns, Reference )
plt.plot(x, y, 'r')  # Reference will say what graph we are modding
plt.subplot(1, 2, 2)
plt.plot(y, x, 'g')
plt.show()

代码将创建如下图:

enter image description here

您可以使用plt.xlabel('name')plt.ylabel('name')plt.title('name')来定义图形的标签和标题

注意:上面的代码将创建一个包含2个图形的图像,您可以在另一个代码块中使用此代码来创建所需的图像。

您还可以使用以下代码:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=5, ncols=5, figsize=(5, 5))
ax[0, 0].plot(x, y)  # The method ax is now one array and is referred by indexes
ax[0, 0].set_title('Title')
ax[1, 1].plot(x, y)
ax[1, 1].set_title('Title')
plt.tight_layout()  # It will separate the graphs to avoid overlays
plt.show()

它将创建以下图像:

enter image description here