keep matplotlib / pyplot windows open after code termination

2024/10/11 8:29:10

I'd like python to make a plot, display it without blocking the control flow, and leave the plot open after the code exits. Is this possible?

This, and related subjects exist (see below) in numerous other threads, but I can't get the plot to both stay open, and be non-blocking. For example, if I use pyplot.ion() before pyplot.show(), or if I use pyplot.show(block=False) then the plot closes when the code terminates. This is true using either python or ipython. If it matters, I'm running on OS X 10.8.2 (Mountain Lion), running python27 and ipython27

Related discussions:
pylab matplotlib "show" waits until window closes
Is there a way to detach matplotlib plots so that the computation can continue?
Keep plotting window open in Matplotlib
Closing pyplot windows

Answer

On Linux you can detach the display this way:

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import osdef detach_display():mu, sigma = 0, 0.5x = np.linspace(-3, 3, 100)plt.plot(x, mlab.normpdf(x, mu, sigma))plt.show()    if os.fork():# Parentpass
else:# Childdetach_display()

The main process ends, but the plot remains.


Attempt #2. This also works on Linux; you might give it a try: but not on OS X.

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import os
import multiprocessing as mpdef detach_display():mu, sigma = 0, 0.5x = np.linspace(-3, 3, 100)plt.plot(x, mlab.normpdf(x, mu, sigma))plt.show()proc = mp.Process(target=detach_display)
proc.start()
os._exit(0)

Without the os._exit(0), the main process blocks. Pressing Ctrl-C kills the main process, but the plot remains.

With the os._exit(0), the main process ends, but the plot remains.


Sigh. Attempt #3. If you place your matplotlib calls in another script, then you could use subprocess like this:

show.py:

import matplotlib.pyplot as plt
import numpy as np
import sysfilename = sys.argv[1]
data = np.load(filename)
plt.plot(data['x'], data['y'])
plt.show()    

test.py

import subprocess
import numpy as np
import matplotlib.mlab as mlabmu, sigma = 0, 0.5
x = np.linspace(-3, 3, 100000)
y = mlab.normpdf(x, mu, sigma)
filename = '/tmp/data.npz'
np.savez(filename, x=x, y=y)
proc = subprocess.Popen(['python', '/path/to/show.py', filename])

Running test.py should display a plot and return control to the terminal while leaving the plot displayed.

https://en.xdnf.cn/q/69792.html

Related Q&A

socket python : recvfrom

I would like to know if socket.recvfrom in python is a blocking function ? I couldnt find my answer in the documentation If it isnt, what will be return if nothing is receive ? An empty string ? In…

pandas read_excel(sheet name = None) returns a dictionary of strings, not dataframes?

The pandas read_excel documentation says that specifying sheet_name = None should return "All sheets as a dictionary of DataFrames". However when I try to use it like so I get a dictionary of…

Plotly: How to assign specific colors for categories? [duplicate]

This question already has an answer here:How to define colors in a figure using Plotly Graph Objects and Plotly Express(1 answer)Closed 2 years ago.I have a pandas dataframe of electricity generation m…

Using nested asyncio.gather() inside another asyncio.gather()

I have a class with various methods. I have a method in that class something like :class MyClass:async def master_method(self):tasks = [self.sub_method() for _ in range(10)]results = await asyncio.gath…

AttributeError: type object Word2Vec has no attribute load_word2vec_format

I am trying to implement word2vec model and getting Attribute error AttributeError: type object Word2Vec has no attribute load_word2vec_formatBelow is the code :wv = Word2Vec.load_word2vec_format("…

Python - Core Speed [duplicate]

This question already has answers here:Getting processor information in Python(12 answers)Closed 8 years ago.Im trying to find out where this value is stored in both windows and osx, in order to do som…

App Engine, transactions, and idempotency

Please help me find my misunderstanding.I am writing an RPG on App Engine. Certain actions the player takes consume a certain stat. If the stat reaches zero the player can take no more actions. I start…

Speed differences between intersection() and object for object in set if object in other_set

Which one of these is faster? Is one "better"? Basically Ill have two sets and I want to eventually get one match from between the two lists. So really I suppose the for loop is more like:f…

Pandas.read_csv reads all of the file into one column

I have a csv file in the form "...","...","..."... with over 40 columns. When I used this simple code, it only gives me one massive key. Ive been messing with it for over …

Python lazy evaluation numpy ndarray

I have a large 2D array that I would like to declare once, and change occasionnaly only some values depending on a parameter, without traversing the whole array. To build this array, I have subclassed …