简体   繁体   English

matplotlib 中的多个图,其中 function 返回 plot

[英]Multiple plots in matplotlib with a function returning a plot

Suppose I have:假设我有:

import matplotlib.pyplot as plt

def generate_plot(data):
    plt.plot(...)
    return plt

we assume that _data is an iterable with length 4.我们假设 _data 是一个长度为 4 的可迭代对象。

if "__name__" = "__main__":
   _data = ....
   plt.figure(1)
   for data_i, index in _data, range(4):
       plt.subplot(2,2,index+1)
       ??????? <---- what goes here?

   plt.savefig(...)

Can I call generate_plot such that the graph plotted is placed in position index?我可以调用 generate_plot 以便将绘制的图形放在 position 索引中吗? If so, how?如果是这样,怎么做?

To be honest, I don't quite understand how the plt object works in Matplotlib.老实说,我不太明白 plt object 在 Matplotlib 中是如何工作的。

You don't want to return plt .您不想return plt You can think of plt just as a way to access all of the plotting things in matplotlib, not as a "plot object".您可以将plt视为访问 matplotlib 中所有绘图内容的一种方式,而不是“绘图对象”。 Generate your data first, then plot it.首先生成您的数据,然后是 plot 它。 Say for example I have比如说我有

import numpy as np
import matplotlib.pyplot as plt

def generate_data():
    return np.random.randint(10, size=10)

plt.figure(1)
for i in range(4):
    plt.subplot(2, 2, i + 1)
    plt.plot(generate_data())

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM