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
Related
Cannot get the following code to do all three things:
stop at the debug breakpoint
render the figure
return control to the console with the figure rendered (in debugger mode)
import matplotlib.pyplot as plt
from ipdb import set_trace
fig, ax = plt.subplots()
ax.plot(range(10))
plt.show()
set_trace()
The use case to do all three things simultaneously is debugging inside of a module that requires information in the matplotlib visualization.
Running IPython from the console as ipython --pylab accomplishes (1) and (3) above only, as shown below. Using plt.ion() in the code does the same. The debugger is available but the visualization will not render.
Running IPython from the console as just ipython, or running python <script.py>, accomplishes (1) and (2) above only, as shown below. The visualization has rendered but the debugger is not available.
Right now I am using python 3.7.7, matplotlib 3.1.3 with Qt5Agg backend, ipython 7.13.0, and ipdb 0.12.3.
If you enable the interactive mode using ion(), you can achieve it while running python <script.py>. It will show the plots (by calling draw) immediately after plot and leave the control back to the console at set_trace.
import matplotlib.pyplot as plt
from ipdb import set_trace
# Enable interactive mode
plt.ion()
fig, ax = plt.subplots()
# Shown immediately
ax.plot(range(10))
set_trace()
Scenario 1
import matplotlib.pyplot as plt
from ipdb import set_trace
fig, ax = plt.subplots()
ax.plot(range(10))
plt.show()
set_trace()
In your example, you are
in ipython,
not in interactive mode.
Hence, plt.show() blocks execution of the rest of the script until the figure is closed.
Scenario 2
import matplotlib.pyplot as plt
from ipdb import set_trace
# Enable interactive mode
plt.ion()
fig, ax = plt.subplots()
ax.plot(range(10))
# Shown immediately
set_trace()
With #ilke444 code you are in interactive mode. However, interactive mode works a little bit differently then #ilke444 expects, given the code comment. It does not force a draw immediately but when control is returned to the REPL, in your case ipython. However, we never get there as we enter the debugger before that happens.
Scenario 3
import matplotlib.pyplot as plt
from ipdb import set_trace
# Enable interactive mode
plt.ion()
fig, ax = plt.subplots()
ax.plot(range(10))
plt.show() # or: fig.canvas.draw() or plt.pause()
set_trace()
#ilke444 suggestion in the comment works because we actually force the figure draw before entering the debugger.
I encountered a similar problem in the following situation:
I am running on debug mode on Pycharm and stopped in a certain place
Then I tried to run a function in the debug console that's supposed to plot figures using matplotlib.pyplot and it didn't
The solution was to actually delete the plt.show() at the end of the function
now it works
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 am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.
I cannot get matplotlib graphics to show up inline.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()
Instead of inline graphics, I get this:
<matplotlib.figure.Figure at 0x110b9c450>
And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.
I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:
c.IPKernelApp.matplotlib=<CaselessStrEnum>
Default: None
Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
Configure matplotlib for interactive use with the default matplotlib backend.
If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.
Ctrl + Enter
%matplotlib inline
Magic Line :D
See: Plotting with Matplotlib.
Use the %pylab inline magic command.
To make matplotlib inline by default in Jupyter (IPython 3):
Edit file ~/.ipython/profile_default/ipython_config.py
Add line c.InteractiveShellApp.matplotlib = 'inline'
Please note that adding this line to ipython_notebook_config.py would not work.
Otherwise it works well with Jupyter and IPython 3.1.0
I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):
It's now recommended that python notebook isn't started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.
See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb
I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.
I did the anaconda install but matplotlib is not plotting
It starts plotting when i did this
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)
You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.
First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.
df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))
df_randNumbers1.ix[:,["A","B"]].plot.kde()
However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.
If you're using Jupyter notebooks in Visual Studio Code (VSCode) then the inline backend doesn't seem to work so you need to specify widget/ipympl (which you may need to install support for e.g. pip install ipympl):
%matplotlib widget
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)
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.
I cannot get matplotlib graphics to show up inline.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()
Instead of inline graphics, I get this:
<matplotlib.figure.Figure at 0x110b9c450>
And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.
I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:
c.IPKernelApp.matplotlib=<CaselessStrEnum>
Default: None
Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
Configure matplotlib for interactive use with the default matplotlib backend.
If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.
Ctrl + Enter
%matplotlib inline
Magic Line :D
See: Plotting with Matplotlib.
Use the %pylab inline magic command.
To make matplotlib inline by default in Jupyter (IPython 3):
Edit file ~/.ipython/profile_default/ipython_config.py
Add line c.InteractiveShellApp.matplotlib = 'inline'
Please note that adding this line to ipython_notebook_config.py would not work.
Otherwise it works well with Jupyter and IPython 3.1.0
I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):
It's now recommended that python notebook isn't started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.
See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb
I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.
I did the anaconda install but matplotlib is not plotting
It starts plotting when i did this
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)
You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.
First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.
df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))
df_randNumbers1.ix[:,["A","B"]].plot.kde()
However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.
If you're using Jupyter notebooks in Visual Studio Code (VSCode) then the inline backend doesn't seem to work so you need to specify widget/ipympl (which you may need to install support for e.g. pip install ipympl):
%matplotlib widget