且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

matplotlib.pyplot:创建存储图的子图

更新时间:2021-07-02 07:03:35

人物是人物.图形中不能有图形.通常的方法是创建一个图形,创建一个或多个子图,在子图中绘制一些东西.

A figure is a figure. You cannot have a figure inside a figure. The usual approach is to create a figure, create one or several subplots, plot something in the subplots.

如果您想在不同的轴或图形中绘制某些内容,将绘图包装在一个以轴为参数的函数中可能是有意义的.

In case it may happen that you want to plot something in different axes or figures, it might make sense to wrap the plotting in a function which takes the axes as argument.

然后,您可以使用此函数绘制新图形的轴或绘制具有许多子图的图形的轴.

You could then use this function to plot to an axes of a new figure or to plot to an axes of a figure with many subplots.

import numpy as np
import matplotlib.pyplot as plt

def myplot(ax, data_x, data_y, color="C0"):
    ax.plot(data_x, data_y, color=color)
    ax.legend()

x = np.linspace(0,10)
y = np.cumsum(np.random.randn(len(x),4), axis=0)

#create 4 figures
for i in range(4):
    fig, ax = plt.subplots()
    myplot(ax, x, y[:,i], color="C{}".format(i))

# create another figure with each plot as subplot
fig, ax = plt.subplots(2,2)
for i in range(4):
    myplot(ax.flatten()[i], x, y[:,i], color="C{}".format(i))

plt.show()