简体   繁体   English

Matplotlib图上的多行

[英]Matplotlib multiple lines on graph

I've been having an issue with saving matplotlib graphs as images. 我一直遇到将matplotlib图保存为图像的问题。 The images are saving differently from what shows up when I call the .show() method on the graph. 当我在图上调用.show()方法时,图像的保存方式与显示的图像不同。 An example is here: http://s1.postimg.org/lbyei5cfz/blue5.png 这里有一个例子: http//s1.postimg.org/lbyei5cfz/blue5.png

I'm not sure what else to do. 我不知道还能做什么。 I've spent the past hours trying to figure out what's causing it, but I can't figure it out. 我花了几个小时试图找出造成它的原因,但我无法弄明白。

Here is my code in it's entirety. 这是我的全部代码。

import matplotlib.pyplot as plt
import random
turn = 1 #for the x values
class Graph():
    def __init__(self, name, color):
        self.currentValue = 5 #for the y values
        self.x = [turn]
        self.y = [self.currentValue]
        self.name = name
        self.color = color 

    def update(self):
        if random.randint(0,1): #just to show if the graph's value goes up or down
            self.currentValue += random.randint(0,10)
            self.y.append(self.currentValue)
        else:
            self.currentValue -= random.randint(0,10)
            self.y.append(self.currentValue)
        self.x.append(turn)

    def plot(self):
        lines = plt.plot(self.x,self.y)
        plt.setp(lines, 'color',self.color)
        plt.savefig(self.name + str(turn))
        #plt.show() will have a different result from plt.savefig(args)

graphs = [Graph("red",'r'),Graph("blue",'b'),Graph("green",'g')]
for i in range(5):
    for i in graphs:
        i.update() #changes the x and y value
        i.plot() #saves the picture of the graph
    turn += 1

Sorry if this is a stupid mistake I'm making, I just find it peculiar how plt.show() and plt.savefig are different. 对不起,如果这是我犯的一个愚蠢的错误,我发现plt.show()和plt.savefig有什么不同。

Thanks for the help. 谢谢您的帮助。

As stated correctly by David, plt.show() resets current figure. 正如David所说, plt.show()重置当前数字。 plt.savefig() , however, does not, so you need to reset it explicitly. 但是, plt.savefig()没有,所以你需要显式重置它。 plt.clf() or plt.figure() are two functions that can do it dor you. plt.clf()plt.figure()是两个可以做到这一点的函数。 Just insert the call right after plt.savefig : 只需在plt.savefig之后插入调用:

    plt.savefig(self.name + str(turn))
    plt.clf()

If you want to save the figure after displaying it, you'll need to hold on to the figure instance. 如果要在显示后保存图形,则需要保持图形实例。 The reason that plt.savefig doesn't work after calling show is that the current figure has been reset. 调用showplt.savefig不起作用的原因是当前数字已被重置。

pyplot keeps track of which figures, axes, etc are "current" (ie have not yet been displayed with show ) behind-the-scenes. pyplot跟踪哪些数字,轴等在幕后是“当前”(即尚未与show一起show )。 gcf and gca get the current figure and current axes instances, respectively. gcfgca获取当前的图形和当前轴实例。 plt.savefig (and essentially any other pyplot method) just does plt.gcf().savefig(...) . plt.savefig (基本上是任何其他pyplot方法)只是plt.gcf().savefig(...) In other words, get the current figure instance and call its savefig method. 换句话说,获取当前的数字实例并调用其savefig方法。 Similarly plt.plot basically does plt.gca().plot(...) . 类似地, plt.plot基本上是plt.gca().plot(...)

After show is called, the list of "current" figures and axes is empty. 调用show后,“当前”图形和轴的列表为空。

In general, you're better off directly using the figure and axes instances to plot/save/show/etc, rather than using plt.plot , etc, to implicitly get the current figure/axes and plot on it. 一般来说,最好直接使用图形和轴实例绘制/保存/显示/等,而不是使用plt.plot等来隐式获取当前图形/轴并在其上绘图。 There's nothing wrong with using pyplot for everything (especially interactively), but it makes it easier to shoot yourself in the foot. pyplot用于所有事情(特别是交互式)没有任何问题,但它更容易在脚下拍摄自己。

Use pyplot for plt.show() and to generate a figure and an axes object(s), but then use the figure or axes methods directly. plt.show()使用pyplot并生成图形和轴对象,然后直接使用图形或轴方法。 (eg ax.plot(x, y) instead of plt.plot(x, y) , etc) The main advantage of this is that it's explicit. (例如ax.plot(x, y)而不是plt.plot(x, y)等)这个的主要优点是它是显式的。 You know what objects you're plotting on, and don't have to reason about what the pyplot state-machine does (though it's not that hard to understand the state-machine interface, either). 你知道你正在绘制什么对象,并且不必推断pyplot状态机的作用(尽管它也不难理解状态机接口)。

As an example of the "recommended" way of doing things, do something like: 作为“推荐”做事方式的一个例子,做一些像:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100)
y = x**2

fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig('fig1.pdf')
plt.show()
fig.savefig('fig2.pdf')

If you'd rather use the pyplot interface for everything, then just grab the figure instance before you call show . 如果你更愿意使用pyplot接口,那么只需在调用show之前抓住图形实例。 For example: 例如:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100)
y = x**2

plt.plot(x, y)
fig = plt.gcf()
fig.savefig('fig1.pdf')
plt.show()
fig.savefig('fig2.pdf')

source 资源

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

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