167

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)]'}
nbro
  • 15,395
  • 32
  • 113
  • 196
Rasmus Larsen
  • 5,721
  • 8
  • 47
  • 79

25 Answers25

186

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()
Vishal Sharma
  • 1,670
  • 20
  • 55
Amit Lohan
  • 2,021
  • 2
  • 8
  • 10
  • 10
    It's really amazing - this worked for me, and none of the others did. What was surprising is, I didn't need plt.show() in Jupyter Notebook, dunno why the behavior is different in PyCharm – Ambareesh Jan 24 '19 at 05:08
  • 1
    same here. I didn't need it in Jupyter Notebook – pooria Sep 02 '19 at 23:38
  • 4
    I always forget to call that too. This tell the system to actually draw it in pycharm. Notebook will auto call draw and print functions by default. I think it was made like that for quicker prototyping. – MNM Jan 26 '20 at 23:47
  • What if I need to use `plt.draw()` since I'm updating the figure later on? `plt.show()` works fine, but `plt.draw()` doesn't show anything in PyCharm. – stefanbschneider May 13 '20 at 06:27
  • 5
    Could be that you don't need it in notebooks because you did something like this `%matplotlib inline`. @CGFox, draw is meant explicitly to render to memory but not display to the screen (or file). You need to either plt.pause(0.1) to get the plots to show, or call plt.show(pause=True) at some other point in code to get them to render – xaviersjs May 22 '20 at 01:01
  • 2
    Am I wrong, or is this answer technically wrong? He uses `import matplotlib as plt` so it would have been `plt.pyplot.show()` or the note, that we use the common `import matplotlib.pyplot as plt`!? – CodePrinz May 03 '21 at 17:43
  • Same for me, I'm used to Spyder which plots automatically – endolith Feb 27 '23 at 22:44
69

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.

Cà phê đen
  • 1,883
  • 2
  • 21
  • 20
user3915686
  • 691
  • 5
  • 2
  • 21
    Adding plt.show(block=True) to the end of my function is what worked for me. Thank you for the clarification. (Python 3.x, PyCharm 2016.1.4, Ubuntu) – SummerEla Jun 03 '16 at 03:30
  • 1
    This is what works for me (Python 2.7, Pycharm 2016.3, Ubuntu 16.04): "import matplotlib.pyplot as plt", then the function plot from DataFrame like in "corr_data[col].plot(kind="bar", figsize=(8, 5), grid=True, color="r", title=col)" and before leaving the function, "plt.show()" – Taka Oct 25 '16 at 18:17
  • 2
    It looks like Pycharm doesn't like interactive mode. Even with it on and a call to `plt.show()` I get a frozen and blank display window. I have to force close python to move on. However, setting `plt.show(block=True)` resulted in the desired behavior. – rocksNwaves Apr 21 '22 at 13:02
37

I had the same problem. Check wether plt.isinteractive() is True. Setting it to 'False' helped for me.

plt.interactive(False)
DanT
  • 3,960
  • 5
  • 28
  • 33
  • 12
    Calling plt.show(block=True) helped showing the chart once for me. But the console was blocked even after closing the charts window. – DanT Jan 26 '15 at 16:13
  • 1
    plt.interactive(False) did it for me in PyCharm – fantabolous Jan 29 '15 at 09:18
  • I don't have Python installed anymore, so I don't know if it would work for me, but since it works for others I'll accept this answer (I hope this is correct according to stackoverflow-rules) – Rasmus Larsen Jan 29 '15 at 09:56
  • 12
    The correct solution is to set plt.show(block=True) as @charlie has suggested below. After you add this line the value of the plt.interactive() flag had no bearing on the plot being displayed. – frostbite Dec 17 '16 at 19:34
  • This didn't work for me ` for cluster_id in range(len(tempx[0])): plt.plot(tempx, tempy, 'rx--', markersize=8) plt.legend(loc=4, framealpha=0.5) plt.interactive(False) plt.show(block=True)` – Mona Jalal Oct 06 '17 at 00:39
37

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.

Keith OYS
  • 2,285
  • 5
  • 32
  • 38
36
import matplotlib
matplotlib.use('TkAgg')

Works for me. (PyCharm/OSX)

Zoe
  • 27,060
  • 21
  • 118
  • 148
Joe Bobson
  • 1,216
  • 15
  • 19
17

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)
tairen
  • 379
  • 3
  • 9
15

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()
Dhruv
  • 151
  • 1
  • 2
  • But I am now facing a new problem. Once the plot is generated in a new window, new code which I added after the plot does not run, until I close the newly opened window. – Dhruv Apr 20 '15 at 23:52
  • 2
    The important line that was missing in the question is plt.show() – Yoav Feb 16 '17 at 07:39
8

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.

Sudeep K Rana
  • 299
  • 3
  • 3
7

None of the above worked for me but the following did:

  1. Disable the checkbox (Show plots in tool window) in pycharm settings > Tools > Python Scientific.

  2. 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.

  • 1
    Please make clearer that the first step could still be the solution, as it worked for me. Stated like this, the other repeating answer of @amir1122 has a right to exist. Which is OK as well of course, and you still got my upvote. – questionto42 Jul 15 '20 at 11:41
  • 1
    @Lorenz. Updated according to your suggestion which makes sense. – AbdulRehmanLiaqat Jul 16 '20 at 12:11
  • 1
    Step 1 works, but feels like a workaround. I suspect in my case that it is because I have multiple versions of Python (3.6, 3.7, and 3.8) floating around. – Josiah Yoder Jul 22 '20 at 18:23
  • 1
    I only unchecked the box and then it showed a window for a quick display and disappeared. After that I added plot.waitforbuttonpress() and now it works perfectly – Amlan Chatterjee Mar 30 '21 at 21:18
6

Just add plt.pyplot.show(), that would be fine.

The best solution is disabling SciView.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Taki Guan
  • 61
  • 1
  • 2
5

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:

  1. Uninstall matplotlib via pip
  2. Install the appropriate libraries: sudo apt-get install tcl-dev tk-dev python-tk python3-tk
  3. Install matplotlib via pip again.
Arie
  • 51
  • 1
  • 1
4

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)
Jon Miles
  • 9,605
  • 11
  • 46
  • 66
m4ndy
  • 43
  • 6
3

My env: macOS & anaconda3

This works for me:

matplotlib.use('macosx')

or interactive mode:

matplotlib.use('TkAgg')
Zoe L
  • 1,150
  • 14
  • 22
3

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

amir1122
  • 57
  • 5
  • 2
    This answer was already provided two years ago (eg in https://stackoverflow.com/a/52221178/466862). When answering older questions, make sure you either answer a new, different solution, or a significantly better explanation. – Mark Rotteveel Mar 24 '20 at 11:56
  • 1
    This is repeating @AbdulRehmanLiaqat's answer, but it at least clearly states that this can be a possible solution. I first downvoted this because of the repetition. Now I upvoted, simply because the other answer does not state clearly that this single step here can already solve it, instead it mentions an error afterwards which did not appear in my case. – questionto42 Jul 15 '20 at 11:40
2

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.

Bastiaan
  • 4,451
  • 4
  • 22
  • 33
2

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.

1

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
Cà phê đen
  • 1,883
  • 2
  • 21
  • 20
Nathan W
  • 11
  • 1
1

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!

1

In non-interactive env, we have to use plt.show(block=True)

tkr_in
  • 135
  • 1
  • 9
1

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.

Azim
  • 1,596
  • 18
  • 34
0

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()
Nilesh Shinde
  • 457
  • 5
  • 10
0

Change import to:

import matplotlib.pyplot as plt

or use this line:

plt.pyplot.show()
Mise
  • 3,267
  • 1
  • 22
  • 22
0

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!

Cà phê đen
  • 1,883
  • 2
  • 21
  • 20
0

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.

0

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

  1. I changed import statement as below (from - to)

from :

import matplotlib.pylab as plt

to:

import matplotlib.pyplot as plt

  1. 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")
  1. use plt.show to display histogram

plt.show()

Tapan Hegde
  • 1,222
  • 1
  • 8
  • 25