[英]Matplotlib: want different plot for each line
I want go through a list composed of lists of floats, and create a different plot for each of these sublists, where the list is the y values and the same x values are used in each figure. 我想遍历由浮点数列表组成的列表,并为每个子列表创建一个不同的图,其中列表为y值,每个图中使用相同的x值。 Each figure should then be saved to my computer. 然后,每个图形都应保存到我的计算机中。
I'm using matplotlib and getting figures saved--but each subsequent figure has still has the data for the sublist(s) that was used to generate the figure before it! 我正在使用matplotlib并保存了图形-但每个后续图形仍具有用于在其之前生成图形的子列表的数据! (eg, my 50th figure has 50 lines on it, but I only want 1.) How can this be fixed? (例如,我的第50个图形上有50条线,但我只想要1条。)如何解决此问题?
This is my code: 这是我的代码:
#list contains y values in sublists
x = 91,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] #my x values, floats, same for each plot
#names[] is defined earlier, is a list of desired figure names
import matplotlib.pyplot as plt
g = 0
for sublist in list:
y = sublist
plt.plot(x,y)
plt.title(names[g])
g = g + 1
plt.savefig(genes[g-1])
Thanks in advance! 提前致谢!
Your plt.plot
creates a figure and axes the first time it is run. 您的plt.plot
会创建一个图形,并在第一次运行时将其轴化。 Every time after that you add a new line into the figure. 之后,每次在图中添加新行。
There are different ways to handle the situation. 有多种方法可以处理这种情况。 You may, eg, create and close the figure every time: 例如,您可以每次创建并关闭图形:
for sublist in list:
y = sublist
fig = plt.figure()
plt.plot(x,y)
plt.title(names[g])
g = g + 1
plt.savefig(genes[g-1])
plt.close(fig)
This is a bit slow, even though it may not be a problem with only few dozen plots. 尽管这可能只有几十个图块就不成问题,但是这有点慢。
Or then you may only change the Y data for each image: 否则,您只能更改每个图像的Y数据:
# create the first image as a template
l = plt.plot(x, list[0])
for sublist in list:
l.set_ydata(sublist)
plt.title(names[g])
g = g + 1
plt.savefig(genes[g-1])
In this case you only change the Y data on each round. 在这种情况下,您只需要在每一轮更改Y数据。
BTW, there are at least the following things I'd change in the code: 顺便说一句,我至少要在代码中更改以下几项:
matplotlib
转向使用matplotlib
的面向对象的方式 list
to something els ( list
is highly reserved) 将名称list
更改为其他名称( list
是高度保留的) g
(the counter) 有更好的方法来处理g
(计数器) You might benefit from showing your code at http://codereview.stackexchange.com . 您可以从http://codereview.stackexchange.com上显示代码中受益。 There you might get a lot of valuable advice! 在那里,您可能会获得很多有价值的建议!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.