标签归档:plot

以最简单的方式将图例添加到Matplotlib中的PyPlot

问题:以最简单的方式将图例添加到Matplotlib中的PyPlot

TL; DR->如何在不创建任何额外变量MatplotlibPyPlot情况下为的线形图创建图例?

请考虑以下图形脚本:

if __name__ == '__main__':
    PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
                total_lengths, sort_times_ins, 'r-',
                total_lengths, sort_times_merge_r, 'g+',
                total_lengths, sort_times_merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()

正如你所看到的,这是一个非常基本的使用matplotlibPyPlot。理想情况下,生成如下图所示的图:

我知道没什么特别的。但是,尚不清楚在何处绘制哪些数据(我正在尝试绘制某些排序算法的数据,长度与所用时间的关系,并且我想确保人们知道哪条线是哪条)。因此,我需要一个图例,不过,请看下面的示例(来自官方网站):

ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)

您将看到我需要创建一个额外的变量ax。如何在图例中添加图例不必创建此额外变量并保持当前脚本的简单性?

TL;DR -> How can one create a legend for a line graph in Matplotlib‘s PyPlot without creating any extra variables?

Please consider the graphing script below:

if __name__ == '__main__':
    PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
                total_lengths, sort_times_ins, 'r-',
                total_lengths, sort_times_merge_r, 'g+',
                total_lengths, sort_times_merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()

As you can see, this is a very basic use of matplotlib‘s PyPlot. This ideally generates a graph like the one below:

Nothing special, I know. However, it is unclear what data is being plotted where (I’m trying to plot the data of some sorting algorithms, length against time taken, and I’d like to make sure people know which line is which). Thus, I need a legend, however, taking a look at the following example below(from the official site):

ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)

You will see that I need to create an extra variable ax. How can I add a legend to my graph without having to create this extra variable and retaining the simplicity of my current script?


回答 0

label=在每个plot()呼叫中添加一个,然后呼叫legend(loc='upper left')

考虑以下示例(使用Python 3.8.0测试):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

从本教程中略作修改:http : //jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

Add a label= to each of your plot() calls, and then call legend(loc='upper left').

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html


回答 1

您可以使用访问Axes实例(axplt.gca()。在这种情况下,您可以使用

plt.gca().legend()

您可以通过label=在每个plt.plot()调用中使用关键字或通过将标签分配为元组或list中的列表来做到这一点legend,如本工作示例所示:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

但是,如果您需要多次访问Axes实例,建议您使用以下命令将其保存到变量ax中:

ax = plt.gca()

然后呼叫ax而不是plt.gca()

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().


回答 2

这是一个帮助您的示例…

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()

Here’s an example to help you out …

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()


回答 3

一个带有图例的正弦和余弦曲线的简单图解。

用过的 matplotlib.pyplot

import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
    x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()

A simple plot for sine and cosine curves with a legend.

Used matplotlib.pyplot

import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
    x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()


回答 4

将标签添加到绘图调用中与绘图系列相对应的每个参数,即 label = "series 1"

然后只需将其添加Pyplot.legend()到脚本的底部,图例将显示这些标签。

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "series 1"

Then simply add Pyplot.legend() to the bottom of your script and the legend will display these labels.


回答 5

您可以添加自定义图例文档

first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first,'g--', second, 'r--')
plt.legend(['First List','Second List'], loc='upper left')
plt.show()

You can add a custom legend documentation

first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first, 'g--', second, 'r--')
plt.legend(['First List', 'Second List'], loc='upper left')
plt.show()


回答 6

    # Dependencies
    import numpy as np
    import matplotlib.pyplot as plt

    #Set Axes
    # Set x axis to numerical value for month
    x_axis_data = np.arange(1,13,1)
    x_axis_data

    # Average weather temp
    points = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44]

    # Plot the line
    plt.plot(x_axis_data, points)
    plt.show()

    # Convert to Celsius C = (F-32) * 0.56
    points_C = [round((x-32) * 0.56,2) for x in points]
    points_C

    # Plot using Celsius
    plt.plot(x_axis_data, points_C)
    plt.show()

    # Plot both on the same chart
    plt.plot(x_axis_data, points)
    plt.plot(x_axis_data, points_C)

    #Line colors
    plt.plot(x_axis_data, points, "-b", label="F")
    plt.plot(x_axis_data, points_C, "-r", label="C")

    #locate legend
    plt.legend(loc="upper left")
    plt.show()
    # Dependencies
    import numpy as np
    import matplotlib.pyplot as plt

    #Set Axes
    # Set x axis to numerical value for month
    x_axis_data = np.arange(1,13,1)
    x_axis_data

    # Average weather temp
    points = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44]

    # Plot the line
    plt.plot(x_axis_data, points)
    plt.show()

    # Convert to Celsius C = (F-32) * 0.56
    points_C = [round((x-32) * 0.56,2) for x in points]
    points_C

    # Plot using Celsius
    plt.plot(x_axis_data, points_C)
    plt.show()

    # Plot both on the same chart
    plt.plot(x_axis_data, points)
    plt.plot(x_axis_data, points_C)

    #Line colors
    plt.plot(x_axis_data, points, "-b", label="F")
    plt.plot(x_axis_data, points_C, "-r", label="C")

    #locate legend
    plt.legend(loc="upper left")
    plt.show()


有没有一种方法可以分离matplotlib图,以便继续计算?

问题:有没有一种方法可以分离matplotlib图,以便继续计算?

在Python解释器中执行了这些指令后,将获得一个带有绘图的窗口:

from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code

不幸的是,show()当程序进行进一步的计算时,我不知道如何继续交互式地探索创建的图形。

有可能吗?有时计算很长,如果可以在检查中间结果时进行计算,则将有所帮助。

After these instructions in the Python interpreter one gets a window with a plot:

from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code

Unfortunately, I don’t know how to continue to interactively explore the figure created by show() while the program does further calculations.

Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.


回答 0

使用matplotlib不会阻塞的呼叫:

使用draw()

from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print 'continue computation'

# at the end call show to ensure window won't close.
show()

使用交互模式:

from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())

print 'continue computation'

# at the end call show to ensure window won't close.
show()

Use matplotlib‘s calls that won’t block:

Using draw():

from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print('continue computation')

# at the end call show to ensure window won't close.
show()

Using interactive mode:

from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())

print('continue computation')

# at the end call show to ensure window won't close.
show()

回答 1

使用关键字“ block”来覆盖阻止行为,例如

from matplotlib.pyplot import show, plot

plot(1)  
show(block=False)

# your code

继续您的代码。

Use the keyword ‘block’ to override the blocking behavior, e.g.

from matplotlib.pyplot import show, plot

plot(1)  
show(block=False)

# your code

to continue your code.


回答 2

最好始终检查您使用的库是否以非阻塞方式支持使用。

但是,如果您需要更通用的解决方案,或者没有其他方法,则可以使用multprocessingpython中包含的模块运行在单独的进程中阻塞的任何内容。计算将继续:

from multiprocessing import Process
from matplotlib.pyplot import plot, show

def plot_graph(*args):
    for data in args:
        plot(data)
    show()

p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()

print 'yay'
print 'computation continues...'
print 'that rocks.'

print 'Now lets wait for the graph be closed to continue...:'
p.join()

这会带来启动新进程的开销,有时在复杂的场景下很难调试,因此我更喜欢其他解决方案(使用matplotlib非阻塞API调用

It is better to always check with the library you are using if it supports usage in a non-blocking way.

But if you want a more generic solution, or if there is no other way, you can run anything that blocks in a separated process by using the multprocessing module included in python. Computation will continue:

from multiprocessing import Process
from matplotlib.pyplot import plot, show

def plot_graph(*args):
    for data in args:
        plot(data)
    show()

p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()

print 'yay'
print 'computation continues...'
print 'that rocks.'

print 'Now lets wait for the graph be closed to continue...:'
p.join()

That has the overhead of launching a new process, and is sometimes harder to debug on complex scenarios, so I’d prefer the other solution (using matplotlib‘s nonblocking API calls)


回答 3

尝试

import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show(block=False)
# other code
# [...]

# Put
plt.show()
# at the very end of your script to make sure Python doesn't bail out
# before you finished examining.

show()文档说:

在非交互模式下,显示所有图形并阻止直到图形被关闭;在交互模式下,除非在从非交互模式更改为交互模式之前创建图形(不推荐),否则它无效。在这种情况下,它会显示数字,但不会阻止。

可以将单个实验性关键字参数block设置为True或False,以覆盖上述阻止行为。

Try

import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show(block=False)
# other code
# [...]

# Put
plt.show()
# at the very end of your script to make sure Python doesn't bail out
# before you finished examining.

The show() documentation says:

In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

A single experimental keyword argument, block, may be set to True or False to override the blocking behavior described above.


回答 4

重要提示:只是为了澄清一些内容。我假设命令在.py脚本中,并且使用例如python script.py从控制台调用脚本。

一个对我有用的简单方法是:

  1. 在show中使用block = False:plt.show(block = False)
  2. 在.py脚本的末尾使用另一个 show()。

script.py文件示例

plt.imshow(*something*)                                                               
plt.colorbar()                                                                             
plt.xlabel("true ")                                                                   
plt.ylabel("predicted ")                                                              
plt.title(" the matrix")  

# Add block = False                                           
plt.show(block = False)

################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################

# the next command is the last line of my script
plt.show()

IMPORTANT: Just to make something clear. I assume that the commands are inside a .py script and the script is called using e.g. python script.py from the console.

A simple way that works for me is:

  1. Use the block = False inside show : plt.show(block = False)
  2. Use another show() at the end of the .py script.

Example of script.py file:

plt.imshow(*something*)                                                               
plt.colorbar()                                                                             
plt.xlabel("true ")                                                                   
plt.ylabel("predicted ")                                                              
plt.title(" the matrix")  

# Add block = False                                           
plt.show(block = False)

################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################

# the next command is the last line of my script
plt.show()


回答 5

您可能需要阅读matplotlib标题为的文档中的本文档:

在python shell中使用matplotlib

You may want to read this document in matplotlib‘s documentation, titled:

Using matplotlib in a python shell


回答 6

就我而言,我想在计算窗口时弹出几个窗口。供参考,方法如下:

from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw() 
print 'continuing computation'
show()

PS。关于matplotlib的OO接口的非常有用的指南

In my case, I wanted to have several windows pop up as they are being computed. For reference, this is the way:

from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw() 
print 'continuing computation'
show()

PS. A quite useful guide to matplotlib’s OO interface.


回答 7

好吧,我很难弄清非阻塞命令.​​..但是最后,我设法重做了“ Cookbook / Matplotlib / Animations-动画选定的绘图元素 ”示例,因此它可以与线程一起使用(并在线程之间传递数据通过全局变量或通过multiprocessPipe)(在Ubuntu 10.04上的Python 2.6.5上)。

可以在以下位置找到该脚本:Animating_selected_plot_elementsthread.py-否则粘贴在下面(带有较少的注释)以供参考:

import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
import pylab as p
import numpy as nx 
import time

import threading 



ax = p.subplot(111)
canvas = ax.figure.canvas

# for profiling
tstart = time.time()

# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)

# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)


# just a plain global var to pass data (from main, to plot update thread)
global mypass

# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()


# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
# parallel with gobject.idle_add(update_line)
def threadMainTest():
    global mypass
    global runthread
    global pipe1main

    print "tt"

    interncount = 1

    while runthread: 
        mypass += 1
        if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
            interncount *= 1.03
        pipe1main.send(interncount)
        time.sleep(0.01)
    return


# main plot / GUI update
def update_line(*args):
    global mypass
    global t0
    global runthread
    global pipe1upd

    if not runthread:
        return False 

    if pipe1upd.poll(): # check first if there is anything to receive
        myinterncount = pipe1upd.recv()

    update_line.cnt = mypass

    # restore the clean slate background
    canvas.restore_region(background)
    # update the data
    line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
    # just draw the animated artist
    ax.draw_artist(line)
    # just redraw the axes rectangle
    canvas.blit(ax.bbox)

    if update_line.cnt>=500:
        # print the timing info and quit
        print 'FPS:' , update_line.cnt/(time.time()-tstart)

        runthread=0
        t0.join(1)   
        print "exiting"
        sys.exit(0)

    return True



global runthread

update_line.cnt = 0
mypass = 0

runthread=1

gobject.idle_add(update_line)

global t0
t0 = threading.Thread(target=threadMainTest)
t0.start() 

# start the graphics update thread
p.show()

print "out" # will never print - show() blocks indefinitely! 

希望这对某人有帮助,
干杯!

Well, I had great trouble figuring out the non-blocking commands… But finally, I managed to rework the “Cookbook/Matplotlib/Animations – Animating selected plot elements” example, so it works with threads (and passes data between threads either via global variables, or through a multiprocess Pipe) on Python 2.6.5 on Ubuntu 10.04.

The script can be found here: Animating_selected_plot_elements-thread.py – otherwise pasted below (with fewer comments) for reference:

import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
import pylab as p
import numpy as nx 
import time

import threading 



ax = p.subplot(111)
canvas = ax.figure.canvas

# for profiling
tstart = time.time()

# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)

# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)


# just a plain global var to pass data (from main, to plot update thread)
global mypass

# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()


# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
# parallel with gobject.idle_add(update_line)
def threadMainTest():
    global mypass
    global runthread
    global pipe1main

    print "tt"

    interncount = 1

    while runthread: 
        mypass += 1
        if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
            interncount *= 1.03
        pipe1main.send(interncount)
        time.sleep(0.01)
    return


# main plot / GUI update
def update_line(*args):
    global mypass
    global t0
    global runthread
    global pipe1upd

    if not runthread:
        return False 

    if pipe1upd.poll(): # check first if there is anything to receive
        myinterncount = pipe1upd.recv()

    update_line.cnt = mypass

    # restore the clean slate background
    canvas.restore_region(background)
    # update the data
    line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
    # just draw the animated artist
    ax.draw_artist(line)
    # just redraw the axes rectangle
    canvas.blit(ax.bbox)

    if update_line.cnt>=500:
        # print the timing info and quit
        print 'FPS:' , update_line.cnt/(time.time()-tstart)

        runthread=0
        t0.join(1)   
        print "exiting"
        sys.exit(0)

    return True



global runthread

update_line.cnt = 0
mypass = 0

runthread=1

gobject.idle_add(update_line)

global t0
t0 = threading.Thread(target=threadMainTest)
t0.start() 

# start the graphics update thread
p.show()

print "out" # will never print - show() blocks indefinitely! 

Hope this helps someone,
Cheers!


回答 8

在许多情况下,将图像另存为.png文件到硬盘驱动器上更为方便。原因如下:

优点:

  • 您可以在过程中随时打开,查看和关闭它。当您的应用程序长时间运行时,这特别方便。
  • 什么都不会弹出,也不用强迫您打开窗户。当您处理许多数字时,这特别方便。
  • 您的图像可供访问以供以后参考,并且在关闭图形窗口时不会丢失。

退税:

  • 我唯一能想到的是,您将必须去查找文件夹并自己打开图像。

In many cases it is more convenient til save the image as a .png file on the hard drive. Here is why:

Advantages:

  • You can open it, have a look at it and close it down any time in the process. This is particularly convenient when your application is running for a long time.
  • Nothing pops up and you are not forced to have the windows open. This is particularly convenient when you are dealing with many figures.
  • Your image is accessible for later reference and is not lost when closing the figure window.

Drawback:

  • The only thing I can think of is that you will have to go and finder the folder and open the image yourself.

回答 9

如果您在控制台中工作,即IPython可以使用plt.show(block=False)其他答案中指出的方法。但是,如果您很懒,则可以键入:

plt.show(0)

会是一样的。

If you are working in console, i.e. IPython you could use plt.show(block=False) as pointed out in the other answers. But if you’re lazy you could just type:

plt.show(0)

Which will be the same.


回答 10

我还必须添加plt.pause(0.001)代码以使其真正在for循环内工作(否则,它将仅显示第一个和最后一个图):

import matplotlib.pyplot as plt

plt.scatter([0], [1])
plt.draw()
plt.show(block=False)

for i in range(10):
    plt.scatter([i], [i+1])
    plt.draw()
    plt.pause(0.001)

I had to also add plt.pause(0.001) to my code to really make it working inside a for loop (otherwise it would only show the first and last plot):

import matplotlib.pyplot as plt

plt.scatter([0], [1])
plt.draw()
plt.show(block=False)

for i in range(10):
    plt.scatter([i], [i+1])
    plt.draw()
    plt.pause(0.001)

回答 11

在我的系统上,show()不会阻止,尽管我希望脚本在继续之前等待用户与图形交互(并使用’pick_event’回调收集数据)。

为了阻止执行直到绘图窗口关闭,我使用了以下命令:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)

# set processing to continue when window closed
def onclose(event):
    fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)

fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

但是请注意,canvas.start_event_loop_default()产生以下警告:

C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
  warnings.warn(str,DeprecationWarning)

尽管脚本仍在运行。

On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using ‘pick_event’ callbacks) before continuing.

In order to block execution until the plot window is closed, I used the following:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)

# set processing to continue when window closed
def onclose(event):
    fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)

fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

Note, however, that canvas.start_event_loop_default() produced the following warning:

C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
  warnings.warn(str,DeprecationWarning)

although the script still ran.


回答 12

我还希望我的绘图显示运行其余代码(然后继续显示),即使有错误(我有时使用绘图进行调试)。我编写了这个小技巧,以便该with语句中的所有图都具有相同的表现。

这可能有点非标准,不建议用于生产代码。这段代码中可能有很多隐藏的“陷阱”。

from contextlib import contextmanager

@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    '''
    To continue excecuting code when plt.show() is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    '''
    import matplotlib.pyplot
    show_original = matplotlib.pyplot.show
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs)
    matplotlib.pyplot.show = show_replacement

    pylab_exists = True
    try:
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists:
        pylab.show = show_replacement

    try:
        yield
    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            show_original()
            print "*********************************************"
            raise
    finally:
        matplotlib.pyplot.show = show_original
        if pylab_exists:
            pylab.show = show_original
    if keep_show_open_on_exit:
        show_original()

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.figure('a')
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])
        pl.show()

        pl.figure('b')
        pl.plot([1,2,3], [4,5,6])
        pl.show()

        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        this_will_surely_cause_an_error

如果/当我实施适当的“使绘图保持打开状态(即使发生错误)并允许显示新绘图”时,我希望脚本在没有用户干预的情况下正确退出(出于批处理目的)。

我可能会使用类似超时问题的“脚本结尾!\ n如果您想中止绘图输出(您有5秒钟),请按 p:“,来自/programming/26704840/corner我的情况下等待用户输入中断的实现

I also wanted my plots to display run the rest of the code (and then keep on displaying) even if there is an error (I sometimes use plots for debugging). I coded up this little hack so that any plots inside this with statement behave as such.

This is probably a bit too non-standard and not advisable for production code. There is probably a lot of hidden “gotchas” in this code.

from contextlib import contextmanager

@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    '''
    To continue excecuting code when plt.show() is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    '''
    import matplotlib.pyplot
    show_original = matplotlib.pyplot.show
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs)
    matplotlib.pyplot.show = show_replacement

    pylab_exists = True
    try:
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists:
        pylab.show = show_replacement

    try:
        yield
    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            show_original()
            print "*********************************************"
            raise
    finally:
        matplotlib.pyplot.show = show_original
        if pylab_exists:
            pylab.show = show_original
    if keep_show_open_on_exit:
        show_original()

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.figure('a')
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])
        pl.show()

        pl.figure('b')
        pl.plot([1,2,3], [4,5,6])
        pl.show()

        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        this_will_surely_cause_an_error

If/when I implement a proper “keep the plots open (even if an error occurs) and allow new plots to be shown”, I would want the script to properly exit if no user interference tells it otherwise (for batch execution purposes).

I may use something like a time-out-question “End of script! \nPress p if you want the plotting output to be paused (you have 5 seconds): ” from https://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation.


回答 13

plt.figure(1)
plt.imshow(your_first_image)

plt.figure(2)
plt.imshow(your_second_image)

plt.show(block=False) # That's important 

raw_input("Press ENTER to exist") # Useful when you run your Python script from the terminal and you want to hold the running to see your figures until you press Enter
plt.figure(1)
plt.imshow(your_first_image)

plt.figure(2)
plt.imshow(your_second_image)

plt.show(block=False) # That's important 

raw_input("Press ENTER to exist") # Useful when you run your Python script from the terminal and you want to hold the running to see your figures until you press Enter

回答 14

OP询问有关拆除matplotlib地块的问题。大多数答案都假定命令是从python解释器中执行的。此处提供的用例是我偏爱在运行a的终端(例如bash)中测试代码,file.py并且您希望绘制图但python脚本完成并返回命令提示符。

此独立文件用于multiprocessing启动一个单独的过程,以使用绘制数据matplotlib。主线程退出使用os._exit(1)中提到的这个职位。的os._exit()主要退出,但叶势力matplotlib子进程还活着,直到响应关闭绘图窗口。完全是一个单独的过程。

这种方法有点像Matlab开发会话,其中包含带有响应命令提示符的图形窗口。使用这种方法,您已经失去了与图形窗口过程的所有联系,但是,可以进行开发和调试。只需关闭窗口并继续测试即可。

multiprocessing专为仅python代码执行而设计,这使其可能比更加适合subprocessmultiprocessing是跨平台的,因此几乎不需要调整就可以在Windows或Mac中正常运行。无需检查基础操作系统。这已在Linux Ubuntu 18.04LTS上进行了测试。

#!/usr/bin/python3

import time
import multiprocessing
import os

def plot_graph(data):
    from matplotlib.pyplot import plot, draw, show
    print("entered plot_graph()")
    plot(data)
    show() # this will block and remain a viable process as long as the figure window is open
    print("exiting plot_graph() process")

if __name__ == "__main__":
    print("starting __main__")
    multiprocessing.Process(target=plot_graph, args=([1, 2, 3],)).start()
    time.sleep(5)
    print("exiting main")
    os._exit(0) # this exits immediately with no cleanup or buffer flushing

运行file.py将显示一个图形窗口,然后__main__退出,但是multiprocessing+ matplotlib图形窗口仍然通过缩放,平移和其他按钮响应,因为它是独立的过程。

使用以下命令在bash命令提示符下检查进程:

ps ax|grep -v grep |grep file.py

The OP asks about detatching matplotlib plots. Most answers assume command execution from within a python interpreter. The use-case presented here is my preference for testing code in a terminal (e.g. bash) where a file.py is run and you want the plot(s) to come up but the python script to complete and return to a command prompt.

This stand-alone file uses multiprocessing to launch a separate process for plotting data with matplotlib. The main thread exits using the os._exit(1) mentioned in this post. The os._exit() forces main to exit but leaves the matplotlib child process alive and responsive until the plot window is closed. It’s a separate process entirely.

This approach is a bit like a Matlab development session with figure windows that come up with a responsive command prompt. With this approach, you have lost all contact with the figure window process, but, that’s ok for development and debugging. Just close the window and keep testing.

multiprocessing is designed for python-only code execution which makes it perhaps better suited than subprocess. multiprocessing is cross-platform so this should work well in Windows or Mac with little or no adjustment. There is no need to check the underlying operating system. This was tested on linux, Ubuntu 18.04LTS.

#!/usr/bin/python3

import time
import multiprocessing
import os

def plot_graph(data):
    from matplotlib.pyplot import plot, draw, show
    print("entered plot_graph()")
    plot(data)
    show() # this will block and remain a viable process as long as the figure window is open
    print("exiting plot_graph() process")

if __name__ == "__main__":
    print("starting __main__")
    multiprocessing.Process(target=plot_graph, args=([1, 2, 3],)).start()
    time.sleep(5)
    print("exiting main")
    os._exit(0) # this exits immediately with no cleanup or buffer flushing

Running file.py brings up a figure window, then __main__ exits but the multiprocessing + matplotlib figure window remains responsive with zoom, pan, and other buttons because it is an independent process.

Check the processes at the bash command prompt with:

ps ax|grep -v grep |grep file.py


回答 15

我认为,该线程中的答案提供的方法不适用于每个系统,并且无法在更复杂的情况下(例如动画)使用。我建议在以下线程中查看MiKTeX的答案,该线程中找到了一种可靠的方法: 如何等待matplotlib动画结束?

In my opinion, the answers in this thread provide methods which don’t work for every systems and in more complex situations like animations. I suggest to have a look at the answer of MiKTeX in the following thread, where a robust method has been found: How to wait until matplotlib animation ends?


回答 16

如果您想打开多个图形,同时将它们全部打开,则此代码对我有用:

show(block=False)
draw()

If you want to open multiple figures, while keeping them all opened, this code worked for me:

show(block=False)
draw()

回答 17

虽然没有直接回答OP的请求,但我发布了此变通办法,因为它可能会在这种情况下帮助某些人:

  • 我用pyinstaller创建了一个.exe文件,因为我无法在需要生成绘图的位置安装python,所以我需要python脚本来生成绘图,将其另存为.png,关闭它并继续进行下一个,实现为多个绘图循环或使用函数。

为此我使用:

import matplotlib.pyplot as plt
#code generating the plot in a loop or function
#saving the plot
plt.savefig(var+'_plot.png',bbox_inches='tight', dpi=250) 
#you can allways reopen the plot using
os.system(var+'_plot.png') # unfortunately .png allows no interaction.
#the following avoids plot blocking the execution while in non-interactive mode
plt.show(block=False) 
#and the following closes the plot while next iteration will generate new instance.
plt.close() 

其中“ var”标识循环中的图,因此不会被覆盖。

While not directly answering OPs request, Im posting this workaround since it may help somebody in this situation:

  • Im creating an .exe with pyinstaller since I cannot install python where I need to generate the plots, so I need the python script to generate the plot, save it as .png, close it and continue with the next, implemented as several plots in a loop or using a function.

for this Im using:

import matplotlib.pyplot as plt
#code generating the plot in a loop or function
#saving the plot
plt.savefig(var+'_plot.png',bbox_inches='tight', dpi=250) 
#you can allways reopen the plot using
os.system(var+'_plot.png') # unfortunately .png allows no interaction.
#the following avoids plot blocking the execution while in non-interactive mode
plt.show(block=False) 
#and the following closes the plot while next iteration will generate new instance.
plt.close() 

Where “var” identifies the plot in the loop so it wont be overwritten.


回答 18

使用plt.show(block=False)和在脚本调用的结尾plt.show()

这将确保脚本完成后不会关闭窗口。

Use plt.show(block=False), and at the end of your script call plt.show().

This will ensure that the window won’t be closed when the script is finished.


删除matplotlib图中的xticks?

问题:删除matplotlib图中的xticks?

我有一个Semilogx图,我想删除xticks。我试过了:

plt.gca().set_xticks([])
plt.xticks([])
ax.set_xticks([])

网格消失(确定),但仍保留小刻度线(在主刻度线的位置)。如何删除它们?

I have a semilogx plot and I would like to remove the xticks. I tried:

plt.gca().set_xticks([])
plt.xticks([])
ax.set_xticks([])

The grid disappears (ok), but small ticks (at the place of the main ticks) remain. How to remove them?


回答 0

tick_params方法对于这样的事情非常有用。此代码关闭主要和次要刻度线,并从x轴删除标签。

from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False,         # ticks along the top edge are off
    labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()

The tick_params method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.

from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False,         # ticks along the top edge are off
    labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()


回答 1

不完全是OP的要求,但是禁用所有轴线,刻度和标签的简单方法是简单地调用:

plt.axis('off')

Not exactly what the OP was asking for, but a simple way to disable all axes lines, ticks and labels is to simply call:

plt.axis('off')

回答 2

另外,您可以传递一个空的刻度位置并将其标记为

# for matplotlib.pyplot
# ---------------------
plt.xticks([], [])
# for axis object
# ---------------
# from Anakhand May 5 at 13:08
# for major ticks
ax.set_xticks([])
# for minor ticks
ax.set_xticks([], minor=True)

Alternatively, you can pass an empty tick position and label as

# for matplotlib.pyplot
# ---------------------
plt.xticks([], [])
# for axis object
# ---------------
# from Anakhand May 5 at 13:08
# for major ticks
ax.set_xticks([])
# for minor ticks
ax.set_xticks([], minor=True)

回答 3

这是我在matplotlib邮件列表中找到的替代解决方案:

import matplotlib.pylab as plt

x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none') 

Here is an alternative solution that I found on the matplotlib mailing list:

import matplotlib.pylab as plt

x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none') 


回答 4

有比John Vinyard提供的解决方案更好,更简单的解决方案。用途NullLocator

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.show()
plt.savefig('plot')

希望能有所帮助。

There is a better, and simpler, solution than the one given by John Vinyard. Use NullLocator:

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.show()
plt.savefig('plot')

Hope that helps.


回答 5

尝试删除标签(但不删除刻度):

import matplotlib.pyplot as plt

plt.setp( ax.get_xticklabels(), visible=False)

Try this to remove the labels (but not the ticks):

import matplotlib.pyplot as plt

plt.setp( ax.get_xticklabels(), visible=False)

example


回答 6

此代码片段可能仅有助于删除xtick。

from matplotlib import pyplot as plt    
plt.xticks([])

此代码片段可能有助于同时删除xtick和yticks。

from matplotlib import pyplot as plt    
plt.xticks([]),plt.yticks([])

This snippet might help in removing the xticks only.

from matplotlib import pyplot as plt    
plt.xticks([])

This snippet might help in removing the xticks and yticks both.

from matplotlib import pyplot as plt    
plt.xticks([]),plt.yticks([])

回答 7

# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

回答 8

那些正在寻找一个简短的命令来关闭所有刻度线和标签的人应该可以

plt.tick_params(top=False, bottom=False, left=False, right=False, labelleft=False, labelbottom=False)

bool从版本matplotlib> = 2.1.1开始,允许输入各个参数

对于自定义刻度线设置,文档非常有用:

https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html

Those of you looking for a short command to switch off all ticks and labels should be fine with

plt.tick_params(top=False, bottom=False, left=False, right=False,
                labelleft=False, labelbottom=False)

which allows type bool for respective parameters since version matplotlib>=2.1.1

For custom tick settings, the docs are helpful:

https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html


在Matplotlib图中隐藏轴文本

问题:在Matplotlib图中隐藏轴文本

我正在尝试在两个轴上绘制一个没有刻度或数字的图形(我使用传统意义上的轴,而不是matplotlib命名法!)。我遇到的一个问题是matplotlib通过减去值N来调整x(y)ticklabel,然后在轴的末端添加N。

这可能含糊其词,但以下简化示例突出了该问题,其中“ 6.18”是N的有问题的值:

import matplotlib.pyplot as plt
import random
prefix = 6.18

rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
    xlabel_i.set_visible(False)
    xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():
    xlabel_i.set_fontsize(0.0)
    xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
    tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)

plt.show()

我想知道的三件事是:

  1. 如何关闭这一行为在首位(虽然在大多数情况下,它是有用的,它并不总是!)我已经通过看matplotlib.axis.XAxis,并不能找到任何合适

  2. 如何使N消失(即X.set_visible(False)

  3. 无论如何,还有更好的方法来做上述事情吗?如果可以的话,我的最终绘图将是图中的4×4子图。

I’m trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.

This may be vague, but the following simplified example highlights the issue, with ‘6.18’ being the offending value of N:

import matplotlib.pyplot as plt
import random
prefix = 6.18

rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
    xlabel_i.set_visible(False)
    xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():
    xlabel_i.set_fontsize(0.0)
    xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
    tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)

plt.show()

The three things I would like to know are:

  1. How to turn off this behaviour in the first place (although in most cases it is useful, it is not always!) I have looked through matplotlib.axis.XAxis and cannot find anything appropriate

  2. How can I make N disappear (i.e. X.set_visible(False))

  3. Is there a better way to do the above anyway? My final plot would be 4×4 subplots in a figure, if that is relevant.


回答 0

除了隐藏每个元素,您还可以隐藏整个轴:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

或者,您可以将刻度线设置为空列表:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

在第二个选项中,您仍然可以使用plt.xlabel()plt.ylabel()在轴上添加标签。

Instead of hiding each element, you can hide the whole axis:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

Or, you can set the ticks to an empty list:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.


回答 1

如果要仅隐藏保留网格线的轴文本:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

set_visible(False)set_ticks([])也将隐藏网格线。

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.


回答 2

如果您像我一样,并且ax在绘制图形时并不总是检索轴,则一个简单的解决方案是

plt.xticks([])
plt.yticks([])

If you are like me and don’t always retrieve the axes, ax, when plotting the figure, then a simple solution would be to do

plt.xticks([])
plt.yticks([])

回答 3

有点旧的线程,但是,这似乎是使用最新版本的matplotlib的更快方法:

设置x轴的主要格式

ax.xaxis.set_major_formatter(plt.NullFormatter())

Somewhat of an old thread but, this seems to be a faster method using the latest version of matplotlib:

set the major formatter for the x-axis

ax.xaxis.set_major_formatter(plt.NullFormatter())

回答 4

我实际上无法根据此处的任何代码段(甚至答案中接受的代码段)绘制没有边界或轴数据的图像。在浏览了一些API文档之后,我使用了这段代码来渲染图像

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

我使用该tick_params调用基本上关闭了可能呈现的任何其他信息,并且在输出文件中有一个完美的图形。

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.


回答 5

我已经对该图进行了颜色编码以简化此过程。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

您可以使用以下命令完全控制图形,以完成答案,我还添加了对样条线的控制:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)

I’ve colour coded this figure to ease the process.

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

You can have full control over the figure using these commands, to complete the answer I’ve add also the control over the splines:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)

回答 6

使用面向对象的API时,该Axes对象有两种用于删除轴文本的有用方法,set_xticklabels()set_xticks()

假设您使用

fig, ax = plt.subplots(1)
ax.plot(x, y)

如果您只想删除刻度线标签,则可以使用

ax.set_xticklabels([])

或完全删除刻度线,您可以使用

ax.set_xticks([])

这些方法对于准确指定刻度线的位置以及如何标记刻度线很有用。传递空列表将分别导致没有滴答声或标签。

When using the object oriented API, the Axes object has two useful methods for removing the axis text, set_xticklabels() and set_xticks().

Say you create a plot using

fig, ax = plt.subplots(1)
ax.plot(x, y)

If you simply want to remove the tick labels, you could use

ax.set_xticklabels([])

or to remove the ticks completely, you could use

ax.set_xticks([])

These methods are useful for specifying exactly where you want the ticks and how you want them labeled. Passing an empty list results in no ticks, or no labels, respectively.


回答 7

一种技巧可能是将刻度标签的颜色设置为白色以隐藏它!

plt.xticks(color='w')
plt.yticks(color='w')

One trick could be setting the color of tick labels as white to hide it!

plt.xticks(color='w')
plt.yticks(color='w')

您如何更改用matplotlib绘制的图形的大小?

问题:您如何更改用matplotlib绘制的图形的大小?

如何更改用matplotlib绘制的图形的大小?

How do you change the size of figure drawn with matplotlib?


回答 0

该图告诉您呼叫签名:

from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

figure(figsize=(1,1)) 会创建一个一英寸一英寸的图像,该图像将是80 x 80像素,除非您还指定了不同的dpi参数。

figure tells you the call signature:

from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

figure(figsize=(1,1)) would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument.


回答 1

如果您已经创建了图形,则可以快速执行以下操作:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

要将大小更改传播到现有的GUI窗口,请添加 forward=True

fig.set_size_inches(18.5, 10.5, forward=True)

If you’ve already got the figure created you can quickly do this:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

To propagate the size change to an existing gui window add forward=True

fig.set_size_inches(18.5, 10.5, forward=True)

回答 2

弃用说明:
根据官方Matplotlib指南pylab不再建议使用该模块。请考虑使用该matplotlib.pyplot模块,如该其他答案所述

以下似乎有效:

from pylab import rcParams
rcParams['figure.figsize'] = 5, 10

这使图形的宽度为5英寸,高度为10 英寸

然后,Figure类将其用作其参数之一的默认值。

Deprecation note:
As per the official Matplotlib guide, usage of the pylab module is no longer recommended. Please consider using the matplotlib.pyplot module instead, as described by this other answer.

The following seems to work:

from pylab import rcParams
rcParams['figure.figsize'] = 5, 10

This makes the figure’s width 5 inches, and its height 10 inches.

The Figure class then uses this as the default value for one of its arguments.


回答 3

使用plt.rcParams

如果您想在不使用图形环境的情况下更改大小,也可以使用此解决方法。因此,plt.plot()例如在使用时,可以设置宽度和高度的元组。

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)

当您以内联方式绘制时(例如,使用IPython Notebook),这非常有用。正如@asamaier所注意的那样,最好不要将此语句放在import语句的同一单元格中。

转换为厘米

figsize元组接受英寸所以,如果你想将其设置成你必须2.54分他们厘米,看一下这个问题

USING plt.rcParams

There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)

This is very useful when you plot inline (e.g. with IPython Notebook). As @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

Conversion to cm

The figsize tuple accepts inches so if you want to set it in centimetres you have to divide them by 2.54 have a look to this question.


回答 4

请尝试以下简单代码:

from matplotlib import pyplot as plt
plt.figure(figsize=(1,1))
x = [1,2,3]
plt.plot(x, x)
plt.show()

在绘制之前,需要设置图形尺寸。

Please try a simple code as following:

from matplotlib import pyplot as plt
plt.figure(figsize=(1,1))
x = [1,2,3]
plt.plot(x, x)
plt.show()

You need to set the figure size before you plot.


回答 5

如果您正在寻找一种方法来更改Pandas中的图形大小,可以执行例如:

df['some_column'].plot(figsize=(10, 5))

df熊猫数据框在哪里。或者,使用现有图形或轴

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

如果要更改默认设置,可以执行以下操作:

import matplotlib

matplotlib.rc('figure', figsize=(10, 5))

In case you’re looking for a way to change the figure size in Pandas, you could do e.g.:

df['some_column'].plot(figsize=(10, 5))

where df is a Pandas dataframe. Or, to use existing figure or axes

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

If you want to change the default settings, you could do the following:

import matplotlib

matplotlib.rc('figure', figsize=(10, 5))

回答 6

Google中的第一个链接'matplotlib figure size'AdjustingImageSize页面的Google缓存)。

这是上一页的测试脚本。它创建test[1-3].png同一图像的不同大小的文件:

#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib

"""

import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.

import pylab
import numpy as np

# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

pylab.plot(x,y)
F = pylab.gcf()

# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI

# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image

# Now make the image twice as big, making all the fonts and lines
# bigger too.

F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.

输出:

using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8.  6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16.  12.]
Size in Inches [ 16.  12.]

两个注意事项:

  1. 模块注释和实际输出不同。

  2. 通过此答案,可以轻松地将所有三个图像合并到一个图像文件中,以查看大小的差异。

The first link in Google for 'matplotlib figure size' is AdjustingImageSize (Google cache of the page).

Here’s a test script from the above page. It creates test[1-3].png files of different sizes of the same image:

#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib

"""

import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.

import pylab
import numpy as np

# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

pylab.plot(x,y)
F = pylab.gcf()

# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI

# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image

# Now make the image twice as big, making all the fonts and lines
# bigger too.

F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.

Output:

using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8.  6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16.  12.]
Size in Inches [ 16.  12.]

Two notes:

  1. The module comments and the actual output differ.

  2. This answer allows easily to combine all three images in one image file to see the difference in sizes.


回答 7

您可以简单地使用(来自matplotlib.figure.Figure):

fig.set_size_inches(width,height)

从Matplotlib 2.0.0开始,对画布的更改将立即可见,因为forward关键字默认为True

如果您只想更改宽度高度而不是两者,则可以使用

fig.set_figwidth(val) 要么 fig.set_figheight(val)

这些也将立即更新您的画布,但仅限于Matplotlib 2.2.0和更高版本。

对于较旧的版本

您需要forward=True明确指定以便实时更新比上面指定的版本更早的画布。请注意,在Matplotlib 1.5.0之前的版本中,set_figwidthand set_figheight函数不支持该forward参数。

You can simply use (from matplotlib.figure.Figure):

fig.set_size_inches(width,height)

As of Matplotlib 2.0.0, changes to your canvas will be visible immediately, as the forward keyword defaults to True.

If you want to just change the width or height instead of both, you can use

fig.set_figwidth(val) or fig.set_figheight(val)

These will also immediately update your canvas, but only in Matplotlib 2.2.0 and newer.

For Older Versions

You need to specify forward=True explicitly in order to live-update your canvas in versions older than what is specified above. Note that the set_figwidth and set_figheight functions don’t support the forward parameter in versions older than Matplotlib 1.5.0.


回答 8

import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()

您还可以使用:

fig, ax = plt.subplots(figsize=(20, 10))
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()

You can also use:

fig, ax = plt.subplots(figsize=(20, 10))

回答 9

尝试注释掉该fig = ...

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2

fig = plt.figure(figsize=(18, 18))
plt.scatter(x, y, s=area, alpha=0.5)
plt.show()

Try commenting out the fig = ... line

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2

fig = plt.figure(figsize=(18, 18))
plt.scatter(x, y, s=area, alpha=0.5)
plt.show()

回答 10

这对我来说很好:

from matplotlib import pyplot as plt

F = plt.gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.
plt.show() # or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

这也可能会有所帮助:http : //matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html

This works well for me:

from matplotlib import pyplot as plt

F = plt.gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.
plt.show() # or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html


回答 11

要增加N倍的图形大小,您需要在pl.show()之前插入它:

N = 2
params = pl.gcf()
plSize = params.get_size_inches()
params.set_size_inches( (plSize[0]*N, plSize[1]*N) )

它也可以与ipython notebook一起很好地工作。

To increase size of your figure N times you need to insert this just before your pl.show():

N = 2
params = pl.gcf()
plSize = params.get_size_inches()
params.set_size_inches( (plSize[0]*N, plSize[1]*N) )

It also works well with ipython notebook.


回答 12

由于Matplotlib 本身无法使用公制,因此,如果要以合理的长度单位(例如厘米)指定图形的大小,则可以执行以下操作(来自gns-ank的代码):

def cm2inch(*tupl):
    inch = 2.54
    if isinstance(tupl[0], tuple):
        return tuple(i/inch for i in tupl[0])
    else:
        return tuple(i/inch for i in tupl)

然后,您可以使用:

plt.figure(figsize=cm2inch(21, 29.7))

Since Matplotlib isn’t able to use the metric system natively, if you want to specify the size of your figure in a reasonable unit of length such as centimeters, you can do the following (code from gns-ank):

def cm2inch(*tupl):
    inch = 2.54
    if isinstance(tupl[0], tuple):
        return tuple(i/inch for i in tupl[0])
    else:
        return tuple(i/inch for i in tupl)

Then you can use:

plt.figure(figsize=cm2inch(21, 29.7))

回答 13

即使在绘制图形之后,这也会立即调整图形的大小(至少使用带有matplotlib 1.4.0的Qt4Agg / TkAgg-但不使用MacOSX-):

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)

This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg – but not MacOSX – with matplotlib 1.4.0):

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)

回答 14

概括和简化psihodelia的答案。如果您想将图形的当前大小更改一个因子sizefactor

import matplotlib.pyplot as plt

# here goes your code

fig_size = plt.gcf().get_size_inches() #Get current size
sizefactor = 0.8 #Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size) 

更改当前大小后,可能需要微调子图布局。您可以在图形窗口GUI中执行此操作,也可以通过命令subplots_adjust进行操作

例如,

plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)

Generalizing and simplifying psihodelia’s answer. If you want to change the current size of the figure by a factor sizefactor

import matplotlib.pyplot as plt

# here goes your code

fig_size = plt.gcf().get_size_inches() #Get current size
sizefactor = 0.8 #Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size) 

After changing the current size, it might occur that you have to fine tune the subplot layout. You can do that in the figure window GUI, or by means of the command subplots_adjust

For example,

plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)

回答 15

另一种选择是在matplotlib中使用rc()函数(单位为英寸)

import matplotlib
matplotlib.rc('figure', figsize=[10,5])

Another option, to use the rc() function in matplotlib (the unit is inch)

import matplotlib
matplotlib.rc('figure', figsize=[10,5])

回答 16

您可以通过直接更改图形尺寸

plt.set_figsize(figure=(10, 10))

You directly change the figure size by using

plt.set_figsize(figure=(10, 10))

将绘图保存到图像文件,而不是使用Matplotlib显示

问题:将绘图保存到图像文件,而不是使用Matplotlib显示

我正在编写一个快速脚本来动态生成绘图。我使用下面的代码(来自Matplotlib文档)作为起点:

from pylab import figure, axes, pie, title, show

# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})

show()  # Actually, don't show, just save to foo.png

我不想将图形显示在GUI上,而是要将图形保存到文件(例如foo.png)中,以便可以在批处理脚本中使用它。我怎么做?

I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point:

from pylab import figure, axes, pie, title, show

# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})

show()  # Actually, don't show, just save to foo.png

I don’t want to display the plot on a GUI, instead, I want to save the plot to a file (say foo.png), so that, for example, it can be used in batch scripts. How do I do that?


回答 0

在回答问题后,我想在使用matplotlib.pyplot.savefig时添加一些有用的提示。文件格式可以通过扩展名指定:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

将分别给出栅格化或矢量化的输出,这两个都可能有用。此外,您会发现pylab在图像周围留有大量的空白,通常是不希望的空白。使用以下方法删除它:

savefig('foo.png', bbox_inches='tight')

While the question has been answered, I’d like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, you’ll find that pylab leaves a generous, often undesirable, whitespace around the image. Remove it with:

savefig('foo.png', bbox_inches='tight')

回答 1

正如其他人所说的,plt.savefig()或者fig1.savefig()确实是保存图像的方法。

但是我发现在某些情况下总是显示该图。(例如,在Spyder具有plt.ion():交互模式= On的情况下)。我通过强制关闭巨型循环中的图形窗口来解决此问题plt.close(figure_object)(请参阅文档),因此在循环中没有一百万个开放图形:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

如有需要,您应该可以重新打开该图fig.show()(不必测试自己)。

As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.

However I’ve found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by forcing the closing of the figure window in my giant loop with plt.close(figure_object) (see documentation), so I don’t have a million open figures during the loop:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

You should be able to re-open the figure later if needed to with fig.show() (didn’t test myself).


回答 2

解决方案是:

pylab.savefig('foo.png')

The solution is:

pylab.savefig('foo.png')

回答 3

刚在MatPlotLib文档中找到此链接,可以解决此问题: http

他们说,防止图形弹出的最简单方法是通过使用非交互式后端(例如Agg)matplotib.use(<backend>),例如:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')

我个人还是喜欢使用 plt.close( fig ),因为从那时起,您可以选择隐藏某些图形(在循环过程中),但仍显示图形以进行循环后数据处理。不过,它可能比选择非交互式后端要慢-如果有人对此进行了测试,那将很有趣。

更新:对于Spyder,您通常无法以这种方式设置后端(因为Spyder通常会较早加载matplotlib,从而阻止您使用matplotlib.use())。

而是在Spyder偏好设置中使用plt.switch_backend('Agg')或关闭“ 启用支持 ”,然后运行matplotlib.use('Agg')自己命令。

从这两个提示:

Just found this link on the MatPlotLib documentation addressing exactly this issue: http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear

They say that the easiest way to prevent the figure from popping up is to use a non-interactive backend (eg. Agg), via matplotib.use(<backend>), eg:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')

I still personally prefer using plt.close( fig ), since then you have the option to hide certain figures (during a loop), but still display figures for post-loop data processing. It is probably slower than choosing a non-interactive backend though – would be interesting if someone tested that.

UPDATE: for Spyder, you usually can’t set the backend in this way (Because Spyder usually loads matplotlib early, preventing you from using matplotlib.use()).

Instead, use plt.switch_backend('Agg'), or Turn off “enable support” in the Spyder prefs and run the matplotlib.use('Agg') command yourself.

From these two hints: one, two


回答 4

如果您不喜欢“当前”数字的概念,请执行以下操作:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

If you don’t like the concept of the “current” figure, do:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

回答 5

其他答案是正确的。但是,有时我发现我想稍后再打开图形对象。例如,我可能想更改标签大小,添加网格或进行其他处理。在理想的情况下,我只需要重新运行生成图的代码并修改设置即可。las,世界并不完美。因此,除了保存为PDF或PNG之外,我还添加:

with open('some_file.pkl', "wb") as fp:
    pickle.dump(fig, fp, protocol=4)

这样,以后我可以加载图形对象并根据需要操纵设置。

我还用源代码写出了堆栈, locals()每个函数/方法字典的堆栈,以便以后可以准确地知道是什么产生了该图。

注意:请小心,因为有时此方法会生成巨大的文件。

The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:

with open('some_file.pkl', "wb") as fp:
    pickle.dump(fig, fp, protocol=4)

Like this, I can later load the figure object and manipulate the settings as I please.

I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.

NB: Be careful, as sometimes this method generates huge files.


回答 6

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()

回答 7

在使用plot()和其他函数创建所需的内容之后,可以使用如下子句在绘制到屏幕或文件之间进行选择:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))       # size in inches
# use plot(), etc. to create your plot.

# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)  

if save_file:
    plt.savefig(save_file)
    plt.close(fig)
else:
    plt.show()

After using the plot() and other functions to create the content you want, you could use a clause like this to select between plotting to the screen or to file:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))       # size in inches
# use plot(), etc. to create your plot.

# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)  

if save_file:
    plt.savefig(save_file)
    plt.close(fig)
else:
    plt.show()

回答 8

我使用了以下内容:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

保存数字后,我发现使用plt.show非常重要,否则它将无法正常工作。图以png格式导出

I used the following:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

I found very important to use plt.show after saving the figure, otherwise it won’t work.figure exported in png


回答 9

您可以执行以下操作:

plt.show(hold=False)
plt.savefig('name.pdf')

并记得在关闭GUI图之前先让savefig完成。这样,您可以预先查看图像。

或者,你可以看看它plt.show() 然后关闭GUI,然后再次运行该脚本,但这次替换plt.show()plt.savefig()

或者,您可以使用

fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')

You can either do:

plt.show(hold=False)
plt.savefig('name.pdf')

and remember to let savefig finish before closing the GUI plot. This way you can see the image beforehand.

Alternatively, you can look at it with plt.show() Then close the GUI and run the script again, but this time replace plt.show() with plt.savefig().

Alternatively, you can use

fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')

回答 10

如果像我一样使用Spyder IDE,则必须使用以下命令禁用交互模式:

plt.ioff()

(此命令随科学启动一起自动启动)

如果要再次启用它,请使用:

plt.ion()

If, like me, you use Spyder IDE, you have to disable the interactive mode with :

plt.ioff()

(this command is automatically launched with the scientific startup)

If you want to enable it again, use :

plt.ion()


回答 11

解决方案 :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')

如果确实要显示图像并保存图像,请使用:

%matplotlib inline

import matplotlib

The Solution :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')

If you do want to display the image as well as saving the image use:

%matplotlib inline

after import matplotlib


回答 12

根据问题Matplotlib(pyplot)savefig输出空白图像

请注意一件事:如果使用plt.show,则应在之后plt.savefig,否则将给出空白图像。

详细的例子:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

According to question Matplotlib (pyplot) savefig outputs blank image.

One thing should note: if you use plt.show and it should after plt.savefig, or you will give a blank image.

A detailed example:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()


回答 13

import matplotlib.pyplot as plt
plt.savefig("image.png")

在Jupyter Notebook中,您必须在一个单元格中删除plt.show()并添加plt.savefig(),以及其余的plt代码。该图像仍将显示在笔记本中。

import matplotlib.pyplot as plt
plt.savefig("image.png")

In Jupyter Notebook you have to remove plt.show() and add plt.savefig(), together with the rest of the plt-code in one cell. The image will still show up in your notebook.


回答 14

鉴于今天(提出此问题时尚不可用)很多人将Jupyter Notebook用作python控制台,所以有一种极为简单的方式将图保存为.png,只需从Jupyter Notebook 调用matplotlibpylab类,将图绘制为“内联” ‘jupyter单元格,然后将该图形/图像拖到本地目录。不要忘记 %matplotlib inline第一行!

Given that today (was not available when this question was made) lots of people use Jupyter Notebook as python console, there is an extremely easy way to save the plots as .png, just call the matplotlib‘s pylab class from Jupyter Notebook, plot the figure ‘inline’ jupyter cells, and then drag that figure/image to a local directory. Don’t forget %matplotlib inline in the first line!


回答 15

除了上述内容外,我还添加__file__了名称,以便图片和Python文件获得相同的名称。我还添加了一些参数使它看起来更好:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

回答 16

使用时matplotlib.pyplot,必须先保存您的绘图,然后使用以下两行将其关闭:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window

When using matplotlib.pyplot, you must first save your plot and then close it using these 2 lines:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window

回答 17

如前所述,您可以使用:

import matplotlib.pyplot as plt
plt.savefig("myfig.png")

用于保存您正在显示的任何IPhython图像。或者换个角度(从另一个角度看),如果您曾经使用过开放式简历,或者如果您导入过开放式简历,则可以进行以下工作:

导入cv2

cv2.imwrite(“ myfig.png”,图像)

但这只是万一,如果您需要使用Open CV。否则,plt.savefig()应该足够。

As suggested before, you can either use:

import matplotlib.pyplot as plt
plt.savefig("myfig.png")

For saving whatever IPhython image that you are displaying. Or on a different note (looking from a different angle), if you ever get to work with open cv, or if you have open cv imported, you can go for:

import cv2

cv2.imwrite(“myfig.png”,image)

But this is just in case if you need to work with Open CV. Otherwise plt.savefig() should be sufficient.


回答 18

您可以使用任何扩展名(png,jpg等)并以所需的分辨率保存图像。这是保存您的身材的功能。

import os

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

“ fig_id”是您要用来保存图形的名称。希望能帮助到你:)

You can save your image with any extension(png, jpg,etc.) and with the resolution you want. Here’s a function to save your figure.

import os

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

‘fig_id’ is the name by which you want to save your figure. Hope it helps:)


回答 19

您可以这样做:

def plotAFig():
  plt.figure()
  plt.plot(x,y,'b-')
  plt.savefig("figurename.png")
  plt.close()

You can do it like this:

def plotAFig():
  plt.figure()
  plt.plot(x,y,'b-')
  plt.savefig("figurename.png")
  plt.close()