简体   繁体   English

以循环方式在 matplotlib 图中生成新的 plt.plot 图

[英]generating new plt.plot graphs in matplotlib plot in a loop-like manner

I am trying to plot mutliple datasets in a single plot.我试图在一个图中绘制多个数据集。

when you have only a small number the usual way of doing this is:当你只有很少的数字时,通常的做法是:

import matplotlib.pyplot as plt
y = [1,2,3,4]
x = range(len(y))
plt.plot(x,y)
plt.show()

In my case I am trying to plot 40 different list like y.就我而言,我试图绘制 40 个不同的列表,例如 y。 Obviously明显地

import matplotlib.pyplot as plt
y0 = [1,2,3,4]
y1 = [1,2,3,4]
:
:
y40 = [1,2,3,4]
x = range(len(y0))
plt.plot(x,y0)
plt.plot(x,y1)
:
:
plt.plot(x,y40)
plt.show()

is a pretty idiotic way of doing this... My idea was to write a function that I can call:这样做是一种非常愚蠢的方式......我的想法是编写一个我可以调用的函数:

import matplotlib.pyplot as plt

def plotter(y):
    x = range(len(y))
    plt.plot(x,y)
y = []
for i in range(40):
    y.append([1,2,3,4])
pl = plt.figure()    
for i in range(len(SNR)):
    plotter(y[i])

pl.show()

However this opens a plot window, but closes it immediately.然而,这会打开一个绘图窗口,但会立即关闭它。 What am I doing wrong ?我究竟做错了什么 ?

maybe try something like:也许尝试这样的事情:

fig, ax1 = plt.subplots()    

def plotter(y):
    x = range(len(y)
    ax1.plot(y)

for i in range(len(SNR)):
    plotter(SNR[i])

plt.show()

If you wanted, you could pass an axis object into the plotter function to control how the data is plotted on the graph a bit more.如果需要,您可以将轴对象传递给绘图仪函数,以进一步控制数据在图形上的绘制方式。

EDIT:编辑:

To answer your question about adding the axis object into the function.回答有关将轴对象添加到函数中的问题。 This would allow you to plot different sets of data on different axis.这将允许您在不同的轴上绘制不同的数据集。 So if you had two Y axis's on the graph, you could pass in the second axis and have it plotted against the right-hand y axis.因此,如果图形上有两个 Y 轴,则可以传入第二个轴并将其绘制在右侧 y 轴上。 You could do that like this:你可以这样做:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()   

def plotter(y, axis):
    x = range(len(y)
    axis.plot(y)

datasetA = [1, 2, 3, 4, 5]
datasetB = [9, 8, 7, 6, 5]

plotter(datasetA, ax1)
plotter(datasetB, ax2)

plt.show()

This would plot each of the lists of data on separate axis which you could incorporate into your plotting loop if needed.这将在单独的轴上绘制每个数据列表,如果需要,您可以将其合并到绘图循环中。

EDIT:编辑:

To answer your question about your plots closing immediately.回答您关于您的地块立即关闭的问题。 I'm not sure, but I think that plt.show() has a block parameter, that stops the graph from closing.我不确定,但我认为 plt.show() 有一个block图形关闭的block参数。 I don't think plot() as one, or it may be set to false as a default.我不认为plot()是一个,或者它可能被设置为 false 作为默认值。 (I could be wrong about this, but I'll check it out and if there is a different reason I'll edit my answer again) (我可能错了,但我会检查一下,如果有不同的原因,我会再次编辑我的答案)

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

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