本文介绍了matplotlib.pyplot:创建存储图的子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 3.6 om macmatplotlib 2.1.0使用 matplotlib.pyplot(作为 plt)

python 3.6 om macmatplotlib 2.1.0using matplotlib.pyplot (as plt)

假设我有一些 plt.figures(),我将它们附加到称为对象的图形列表中.当在命令行中时,我执行:figures[0]它生成列表 figures 的索引 0 的图.但是,我如何安排将数字中的所有图都放在一个子图中.

Let's say i have a few plt.figures() that i appended into a list called figures as objects. When in command line i do: figures[0]it produces the plot for the index 0 of the list figures.However, how can i arrange to have all the plots in figures to be in a subplot.

# Pseudo code:
plt.figure()
for i, fig in enumerate(figures):   # figures contains the plots
    plt.subplot(2, 2, i+1)
    fig   # location i+1 of the subplot is filled with the fig plot element

因此,我会生成一个 2 x 2 的网格,其中包含图中的每个图.

So as a result, i would a 2 by 2 grid that contains each plot found in figures.

希望这是有道理的.

推荐答案

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

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()

这篇关于matplotlib.pyplot:创建存储图的子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:46