I am trying to use matplotlib to view an image in ipython. However, I solely obtain a description of the image as opposed to seeing the actual image:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> plt.imshow(an_array)
Out[4]: <matplotlib.image.AxesImage at 0x7fb626f063d0>
This is with the backend set to Qt5Agg or TkAgg in .matplotlibrc
I have the same issues whether or not I am working in a conda virtual environment
I am running: Scientific Linux release 6.8 (Carbon), Python 2.7.13, Anaconda 4.3.0 (64-bit)
I have had similar issues on my local computer running MacOSX
I would be most grateful for any advice,
Thanks
Rob
Add %matplotlib inline before import matplotlib.pyplot as plt to enable automatic visualization of your plots when the cell has finished executing.
Note, however, that this works just in iPython notebooks. Normally, you'd need to call plt.show() (without any arguments) to visualize the plots.
Non Code general question: I am running Python 3.5.2 (Anaconda distribution) and new to Python. I want to create a heat map over layed onto map of USA. All searches I've done say use 'basemap' which seems to be unsupported in Python 3. What alternatives are out there (do not want to revert to previous Python).
You can use Seaborn python module it works for python3 as well.
And here is the help regarding heatmap using seaborn.
Or you may use Geoplot python module
geoplot is another library that allows you to create choropleth maps. These can then be overlayed on a webmap using mplleaflet.
Basemap is supported in python 3. With the anaconda install of python 3.7 I used conda install basemap. At this point you might need to set you PROJ_LIB if you are running in the base environment, as shown in the following example script:
import os
os.environ['PROJ_LIB'] = r'C:\Users\YOURUSERNAME\Anaconda3\pkgs\proj4-5.2.0-ha925a31_1\Library\share'
Now you should be able to use basemap in python 3. Here's an example I adapted from Dan Nguyen's github (I removed the Earthquake data and just left the map itself, see the link for neat stuff):
# %matplotlib # in iPython
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
plt.figure(figsize=(14, 8))
earth = Basemap()
earth.bluemarble(alpha=0.42)
earth.drawcoastlines(color='#555566', linewidth=1)
plt.show()
Resultant image:
I have the following code which is regular for anyone who would like to make a plot with pandas in IPython.
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import matplotlib.pyplot as plt
In [4]: %matplotlib inline
Here it pops up an error:
UsageError: Invalid GUI request u'inline', valid ones are: pyglet, osx, qt5, qt, glut, gtk, gtk3, tk, wx
I read this post Run python script in IPython with inline / embedded plots
and found the two methods to get around:
ipython qtconsole --matplotlib inline -m example_plots
or
ipython qtconsole --pylab inline -m example_plots
But none of them works in my situation (I actually got stuck in iPython without making a plot, needless to say a plot embedded within a script.)
I am not sure where went wrong as %matplotlib inline used to work. I am using python 2.7.11 and IPython 4.2.0 if this information helps.
Thank you very much for your help.
I am using
%matplotlib inline
to display plots inside the notebook. I would like to disable this for several cells. So, I try
%matplotlib qt
This outputs the following error:
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
I am not sure how to solve this, as everything is up to date.
How can I solve the above?
Is there another way to disable %matplotlib inline in a certain cell without restarting the entire kernel?
You might be able to use plt.switch_backend, although as the documentation states, this is an experimental feature. The following works for me, using matplotlib 1.5 and an IPython 4.0.1:
In [1]: from matplotlib import pyplot as plt
In [2]: import numpy as np
# plot appears inline (default)
In [3]:plt.plot(np.random.randn(10))
Out[3]:[<matplotlib.lines.Line2D at 0x7fac4408e390>]
In [4]: plt.switch_backend('QtAgg4')
# plot appears inside a separate Qt4 window
In [5]:plt.plot(np.random.randn(10))
Out[5]:[<matplotlib.lines.Line2D at 0x7fac3b408a90>]
You might need to change 'QtAgg4' according to whichever version of PyQt you have installed - this could be the cause of the error you mentioned in the question. Another interactive backend that should work on Mac would be 'CocoaAgg'. If the images are very large you could also use the 'Agg' backend to suppress plotting altogether, and instead save the resulting figure(s) straight to disk.
If you don't have a specific backend installed use "agg":
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
Reference: https://github.com/matplotlib/matplotlib/issues/9017
Pycharm does not show plot from the following code:
import pandas as pd
import numpy as np
import matplotlib as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
What happens is that a window appears for less than a second, and then disappears again.
Using the Pyzo IEP IDE (using same interpreter) on the same code the plot shows as expected.
...So the problem must be with some setting on Pycharm.
I've tried using both python.exe and pythonw.exe as interpreter both with same results.
This is my sys_info:
C:\pyzo2014a\pythonw.exe -u C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevconsole.py 57315 57316
PyDev console: using IPython 2.1.0import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.4.1 |Continuum Analytics, Inc.| (default, May 19 2014, 13:02:30) [MSC v.1600 64 bit (AMD64)] on win32
sys.path.extend(['C:\\Users\\Rasmus\\PycharmProjects\\untitled2'])
In[3]: import IPython
print(IPython.sys_info())
{'commit_hash': '681fd77',
'commit_source': 'installation',
'default_encoding': 'UTF-8',
'ipython_path': 'C:\\pyzo2014a\\lib\\site-packages\\IPython',
'ipython_version': '2.1.0',
'os_name': 'nt',
'platform': 'Windows-8-6.2.9200',
'sys_executable': 'C:\\pyzo2014a\\pythonw.exe',
'sys_platform': 'win32',
'sys_version': '3.4.1 |Continuum Analytics, Inc.| (default, May 19 2014, '
'13:02:30) [MSC v.1600 64 bit (AMD64)]'}
Just use
import matplotlib.pyplot as plt
plt.show()
This command tells the system to draw the plot in Pycharm.
Example:
plt.imshow(img.reshape((28, 28)))
plt.show()
I realize this is old but I figured I'd clear up a misconception for other travelers. Setting plt.pyplot.isinteractive() to False means that the plot will on be drawn on specific commands to draw (i.e. plt.pyplot.show()). Setting plt.pyplot.isinteractive() to True means that every pyplot (plt) command will trigger a draw command (i.e. plt.pyplot.show()). So what you were more than likely looking for is plt.pyplot.show() at the end of your program to display the graph.
As a side note you can shorten these statements a bit by using the following import command import matplotlib.pyplot as plt rather than matplotlib as plt.
I tried different solutions but what finally worked for me was plt.show(block=True). You need to add this command after the myDataFrame.plot() command for this to take effect. If you have multiple plot just add the command at the end of your code. It will allow you to see every data you are plotting.
I had the same problem. Check wether plt.isinteractive() is True. Setting it to 'False' helped for me.
plt.interactive(False)
import matplotlib
matplotlib.use('TkAgg')
Works for me. (PyCharm/OSX)
I test in my version of Pycharm (Community Edition 2017.2.2), you may need to announce both plt.interactive(False) and plt.show(block=True) as following:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 6.28, 100)
plt.plot(x, x**0.5, label='square root')
plt.plot(x, np.sin(x), label='sinc')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("test plot")
plt.legend()
plt.show(block=True)
plt.interactive(False)
I have found a solution. This worked for me:
import numpy as np
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 0.01)
dx, dy = np.meshgrid(points, points)
z = (np.sin(dx)+np.sin(dy))
plt.imshow(z)
plt.colorbar()
plt.title('plot for sin(x)+sin(y)')
plt.show()
Soon after calling
plt.imshow()
call
plt.show(block = True)
You will get the matplotlib popup with the image.
This is a blocking way. Further script will not run until the pop is closed.
None of the above worked for me but the following did:
Disable the checkbox (Show plots in tool window) in pycharm settings > Tools > Python Scientific.
I received the error No PyQt5 module found. Went ahead with the installation of PyQt5 using :
sudo apt-get install python3-pyqt5
Beware that for some only first step is enough and works.
With me the problem was the fact that matplotlib was using the wrong backend. I am using Debian Jessie.
In a console I did the following:
import matplotlib
matplotlib.get_backend()
The result was: 'agg', while this should be 'TkAgg'.
The solution was simple:
Uninstall matplotlib via pip
Install the appropriate libraries: sudo apt-get install tcl-dev tk-dev python-tk python3-tk
Install matplotlib via pip again.
Just add plt.pyplot.show(), that would be fine.
The best solution is disabling SciView.
I tested in my version on PyCharm 2017.1.2. I used interactive (True) and show (block=True).
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1//2000',periods=1000))
ts = ts.cumsum()
plt.interactive(True)
ts.plot()
plt.show(block=True)
My env: macOS & anaconda3
This works for me:
matplotlib.use('macosx')
or interactive mode:
matplotlib.use('TkAgg')
i had this problem and i could solve it , you can test my way..
disable "show plots in tool window" from setting-->tools-->python scientific
Comment from DanT fixed this for me, matplotlib with pycharm on linux with the GTKagg backend. Upon importing matplotlib I would get the following error:
>>> import matplotlib as mpl
Backend GTKAgg is interactive backend. Turning interactive mode on.
Failed to enable GUI event loop integration for 'gtk'
When plotting something like so:
from matplotlib import pyplot as plt
plt.figure()
plt.plot(1,2)
plt.show()
A figure screen would pop up but no charts appear.
using:
plt.show(block=True)
displays the graphic correctly.
For beginners, you might also want to make sure you are running your script in the console, and not as regular Python code. It is fairly easy to highlight a piece of code and run it.
In my case, I wanted to do the following:
plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
plt.show()
Following a mix of the solutions here, my solution was to add before that the following commands:
matplotlib.get_backend()
plt.interactive(False)
plt.figure()
with the following two imports
import matplotlib
import matplotlib.pyplot as plt
It seems that all the commands are necessary in my case, with a MBP with ElCapitan and PyCharm 2016.2.3. Greetings!
In non-interactive env, we have to use plt.show(block=True)
For those who are running a script inside an IDE (and not working in an interactive environment such as a python console or a notebook), I found this to be the most intuitive and the simplest solution:
plt.imshow(img)
plt.waitforbuttonpress()
It shows the figure and waits until the user clicks on the new window. Only then it resume the script and run the rest of the code.
I was able to get a combination of some of the other suggestions here working for me, but only while toggling the plt.interactive(False) to True and back again.
plt.interactive(True)
plt.pyplot.show()
This will flash up the my plots. Then setting to False allowed for viewing.
plt.interactive(False)
plt.pyplot.show()
As noted also my program would not exit until all the windows were closed. Here are some details on my current run environment:
Python version 2.7.6
Anaconda 1.9.2 (x86_64)
(default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)]
Pandas version: 0.13.1
One property need to set for pycharm.
import matplotlib.pyplot as plt
plt.interactive(False) #need to set to False
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
plt.show()
Change import to:
import matplotlib.pyplot as plt
or use this line:
plt.pyplot.show()
I'm using Ubuntu and I tried as #Arie said above but with this line only in terminal:
sudo apt-get install tcl-dev tk-dev python-tk python3-tk
And it worked!
In Pycharm , at times the Matplotlib.plot won't show up.
So after calling plt.show() check in the right side toolbar for SciView. Inside SciView every generated plots will be stored.
I was facing above error when i am trying to plot histogram and below points worked for me.
OS : Mac Catalina 10.15.5
Pycharm Version : Community version 2019.2.3
Python version : 3.7
I changed import statement as below (from - to)
from :
import matplotlib.pylab as plt
to:
import matplotlib.pyplot as plt
and plot statement to below (changed my command form pyplot to plt)
from:
plt.pyplot.hist(df["horsepower"])
# set x/y labels and plot title
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins")
to :
plt.hist(df["horsepower"])
# set x/y labels and plot title
plt.xlabel("horsepower")
plt.ylabel("count")
plt.title("horsepower bins")
use plt.show to display histogram
plt.show()