I am using pandas builtin plotting as per below. However as soon as the plotting method returns, the plot disappears. How can I keep the plot(s) open until I click on them to close?
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
def plot_data():
#...create dataframe df1
pd.options.display.mpl_style = 'default'
df1.boxplot()
df1.hist()
if __name__ == '__main__':
plot_data()
Use a plt.show(block=True) command to keep the plotting windows open.
[...]
df1.boxplot()
df1.hist()
plt.show(block=True)
In my version of matplotlib (1.4.3), block=True is necessary, but that may not be the case for all versions (Keep plotting window open in Matplotlib)
Related
Given a pandas dataframe df, I would like to be able to do the following from terminal:
df.plot()
and have the plot show up in a window automatically, without having to also to the following:
import matplotlib.pyplot as plt;
plt.show()
Is it doable?
You can enable interactive mode when you're in the interactive Python session:
>>> import matplotlib.pyplot as plt
>>> plt.ion()
You can also make that permanent, so you don't have to type plt.ion() every time you start a new session. Just look for "interactive" in your matplotlibrc configuration file and change that line to this:
interactive: True
I have a small Python program that reads from a CSV and prints out a single column (using VSCode).
import pandas as pd
fields = ['Name']
somedata_df = pd.read.csv("somedata.csv")
print(somedata_df[fields])
The above code works as intended and prints out the "Name" column. Simply adding import seaborn as sns or import matplotlib.pyplot as plt causes the program to run as usual with no warnings or errors, but it does not print anything to the terminal.
This issue arose from my exploration as to why I could not produce any plots in a different program. The same thing happened there - program ran without warnings or errors, but did not show any of the plots. No, I did not forget to use matplotlib.pyplot.show().
Even running this example code from Seaborn fails to display a plot:
import seaborn as sns
import matplotib.pyplot as plt
sns.set()
tips = sns.load_dataset("tips")
sns.relplot(x="total_bill", y="tip", col="time",
hue="smoker", style="smoker", size="size",
data=tips)
plt.show()
What is causing this behavior?
Still unsure as to why plots do not show up, and why importing either Matplotlib or Seaborn causes the regular terminal to stop displaying outputs, but selecting the code, right-clicking it, and choosing "Run Selection/Line in Python Interactive Window" works both for the original print statement and any plotting.
I'm trying to make plots in a Jupyter Notebook that update every second or so. Right now, I just have a simple code which is working:
%matplotlib inline
import time
import pylab as plt
import numpy as np
from IPython import display
for i in range(10):
plt.close()
a = np.random.randint(100,size=100)
b = np.random.randint(100,size=100)
fig, ax = plt.subplots(2,1)
ax[0].plot(a)
ax[0].set_title('A')
ax[1].plot(b)
ax[1].set_title('B')
display.clear_output(wait=True)
display.display(plt.gcf())
time.sleep(1.0)
Which updated the plots I have created every second. However, at the end, there is an extra copy of the plots:
Why is it doing this? And how can I make this not happen? Thank you in advance.
The inline backend is set-up so that when each cell is finished executing, any matplotlib plot created in the cell will be displayed.
You are displaying your figure once using the display function, and then the figure is being displayed again automatically by the inline backend.
The easiest way to prevent this is to add plt.close() at the end of the code in your cell.
Another alternative would be to add ; at the end of the line! I am experiencing the same issue with statsmodels methods to plot the autocorrelation of a time series (statsmodels.graphics.tsaplot.plot_acf()):
from statsmodels.graphics.tsaplots import plot_acf
plot_acf(daily_outflow["count"]);
Despite using %matplotlib inline, it's not working for some libraries, such as statsmodels. I recommend always use plt.show() at the end of your code.
Is there a way to close a pyplot figure in OS X using the keyboard (as far as I can see you can only close it by clicking the window close button)?
I tried many key combinations like command-Q, command-W, and similar, but none of them appear to work on my system.
I also tried this code posted here:
#!/usr/bin/env python
import matplotlib.pyplot as plt
plt.plot(range(10))
def quit_figure(event):
if event.key == 'q':
plt.close(event.canvas.figure)
cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)
plt.show()
However, the above doesn't work on OS X either. I tried adding print statements to quit_figure, but it seems like it's never called.
I'm trying this on the latest public OS X, matplotlib version 1.1.1, and the standard Python that comes with OS X (2.7.3). Any ideas on how to fix this? It's very annoying to have to reach for the mouse every time.
This is definitely a bug in the default OS X backend used by pyplot. Adding the following two lines at the top of the file switches to a different backend that works for me, if this helps anyone else.
import matplotlib
matplotlib.use('TKAgg')
I got around this by replacing
plt.show()
with
plt.show(block=False)
input("Hit Enter To Close")
plt.close()
A hack at its best, but I hope that helps someone
use interactive mode:
import matplotlib.pyplot as plt
# Enable interactive mode:
plt.ion()
# Make your plot: No need to call plt.show() in interactive mode
plt.plot(range(10))
# Close the active plot:
plt.close()
# Plots can also be closed via plt.close('all') to close all open plots or
# plt.close(figure_name) for named figures.
Checkout the "What is interactive mode?" section in this documentation
Interactive mode can be turned off at any point with plt.ioff()
When you have focus in the matplotlib window, the official keyboard shortcut is ctrl-W by this:
http://matplotlib.org/1.2.1/users/navigation_toolbar.html
As this is a very un-Mac way to do things, it is actually cmd-W. Not so easy to guess, is it?
If you are using an interactive shell, you can also close the window programmatically. See:
When to use cla(), clf() or close() for clearing a plot in matplotlib?
So, if you use pylab or equivalent (everything in the same namespace), it is just close(fig). If you are loading the libraries manually, you need to take close from the right namespace, for example:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0,1,2],[0,1,0],'r')
fig.show()
plt.close(fig)
The only catch here is that there is no such thing as fig.close even though one would expect. On the other hand, you can use plt.close('all') to regain your desktop.
in windows I try to run this code. Serial works fine and compass value converted to float matplotlib figure opened but matplotlib window "not responding" not draws anything.
import serial
import numpy
import matplotlib.pyplot as plt
ser = serial.Serial('COM8',9600,timeout=2)
ciz,=plt.plot([],[])
def update_ciz(ciz,newdata):
ciz.set_xdata(numpy.append(ciz.get_xdata(),newdata))
ciz.set_ydata(numpy.append(ciz.get_ydata(),newdata))
plt.draw()
while (True):
line = ser.readline()
k=line.split(":")
temperature=k[0]
pressure= k[1]
attitude=k[2]
realAttitude=k[3]
compass=float(k[4])
gx=k[5]
gy=k[6]
gz=k[7]
ax=k[8]
ay=k[9]
az=k[10]
acond=k[11]
update_ciz(ciz,compass)
In matplotlib you need to use "plt.show()" to display the plot. Since you are using "plt.draw()" to update the plot, you probably also want to use the interactive mode.
Try including this after your "ciz,=plt.plot([],[])" command:
plt.ion()
plt.show()