python matplotlib.plot does not show chart - python

Have recently started playing with Python. I have installed Python Spyder app on the Mac. Everything has been working well until recently for some reason the matplotlib charts stopped displaying. A simple code like this does not work anymore:
import matplotlib.pyplot as plt
x = np.linspace(0.4 * np.pi, 100)
plt.plot(x)
The only output is
[]
I have Spyder 2.3.3, Python 3.4.3 64 Bit.

You have to tell the plot to show itself with:
plt.show()

Related

Ubuntu 20.04 - python issue: numpy.linalg.norm() / Matplotlib plot cannot finish execution some code, never returns

I ran into an odd problem with python on Ubuntu recently. My python environment runs fine, except that I cannot execute some basic numpy and matplotlib functions...
Whenever I tried np.linalg.norm(x, ord=2), matplotlib.pyplot.subplots(), or matplotlib.pyplot.plot(), code execution gets stuck at that line and never progresses further, while thread CPU usage hits 100%... Examples below.
I tried this on a few different Anaconda environments running different versions python (3.9, 3.8, 3.7), a fresh Anaconda installation, and with Ubuntu's default Python, all ran into the same problems.
Also because this is happening different libraries, numpy and matplotlib, it makes me think that it might be related to something more fundamental, perhaps related to the Ubuntu OS libraries? Unfortunately, I don't know when exactly this issue started happening, whether it was after some Ubuntu update or python package updates...*
Would any expert here happen to know what could be causing this issue? I'm trying to avoid reinstalling Ubuntu here...
Thank you.
System Info
Ubuntu 20.04 LTS, Linux 5.11.0-40-generic x86_64
NVIDIA-SMI 470.82.00 Driver Version: 470.82.00 CUDA Version: 11.4
2x NVIDIA Geforece 1080Ti
Tried python versions / Anaconda environments:
Anaconda python: 3.9.7, 3.8.12, 3.7.11
Ubuntu default python
Library versions:
numpy 1.21.2
matplotlib 3.5.0 and 3.4.3
ipykernel 6.5.0
notebook 6.4.6
Numpy
With numpy, I noticed that I can run np.linalg.norm() with orders other than 2, but once I set ord=2, the code never finishes running, with CPU hits 100% for this thread.
I tried this in terminal with python and jupyter notebook, same problem...
import numpy as np
z = np.arange(1, 10).reshape(3, 3)
print(np.linalg.norm(z, 1, axis=1))
print(np.linalg.norm(z, np.inf, axis=1))
# code stuck here... doesn't return....
# CPU running at 100% for this thread
print(np.linalg.norm(z, ord=2))
Matplotlib
I ran into the same issue with matplotlib - when I call plt.plot() or plt.subplots():
I also tried to run this in a python script, ran into the same problem.
import matplotlib.pyplot as plt
import matplotlib as M
import numpy as np
x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)
print(f"backend = {M.get_backend()}") # TkAgg
print('create figure...')
fig, ax = plt.subplots() # code execution will be stuck here...
print('calling plot now...')
ax.plot(x, y)
print('calling show()...')
plt.show()

Matplotlib animations do not work in PyCharm

I've found various short files that produce animations using matplotlib. In general, they work fine when run from the command line, but in PyCharm I only get a still frame.
I'm asking the same question as Matplotlib does not update plot when used in an IDE (PyCharm). There's an answer posted there, which seems to work for the original asker. When I run that code from the command line, it works fine. From PyCharm, it pauses for a long time (presumably running the animation) and then shows a still frame (that looks like either the beginning or end of the animation).
I'm running Python 3.6.2 (Anaconda) through PyCharm 2017.3.2 (Professional) on a Mac (OS 10.11.6). I created a Python project in PyCharm, pasted that code into a .py file, installed the appropriate libraries (matplotlib 2.0.2, numpy 1.13.1), and ran the program.
The only difference I can see between this and what I did on the command line is that python --version there gives:
Python 3.6.0 :: Anaconda custom (x86_64)
What else could be the problem?
According to this answer and this ticket, you can disable Show plots in tool window(File->Settings->Tools->Python Scientific) in Pycharm, and I will give an example for this solution.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
The above (or in the link attached) did not work for me, however, i found this works well (running 2.7 with anaconda and ipython console)-
Instead of executing the script normally (using run / Shift+f10), i would first set:
%matplotlib qt5
then execute the script from pycharm console, using
runfile('/path/to/script.py')
resulting in a similar result as if i would do the same from the stand alone ipython console:
(Note - the figure is animated)

python3.6 vispy plot error white screen and data not appear

I have started with vispy but I cannot plot a line of data.
I see a lot of examples which have used package but that doesn't work either.
I have a white window and my line does not appear, why?
This is my code:
import numpy as np
from vispy import plot as vp
fig = vp.Fig(size=(600, 500), show=True)
x=[0,1,2,3,4,5,6]
y=x
line = fig[0, 0].plot((x, y), width=3, color='k')
fig.show()
Can you try:
fig.show(run=True)
It works on my system. Otherwise, it might comes from the pyqt version. I think python 3.6 use pyqt 5 and I'm not sure that vispy is compatible with this version of Qt. If it doesn't works, try to create a python 3.5 environment (it should have pyqt 4 installed). Then re-installed vispy an try your example.

Pycharm does not show plot

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()

Python matplotlib

I'm having trouble getting the window for matplotlib to show.
I've downloaded python 3.3, matplotlib for python 3.3, and numpy.
I've also installed python tools for Visual Studio 2012 so I can create python solutions in that environment.
With all that out of the way... I'm running this EXTREMELY simple script:
import numpy as np
import matplotlib.pyplot as plt
import pylab
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)
# without the line below, the figure won't show
pylab.show()
This compiles with no warnings or errors, but only my console window displays; no graph or interactive window ever shows up. I tried running the scrip from the command prompt thinking maybe the visual studio environment was throwing it off, but it still didn't work.
I also tried running with python 2.7 and it also didn't work.
Every tutorial I found confirmed that this should be working. I'm pulling my hair out and would praise any help at this point.
You should type
plt.show()
instead.
You need to put
plt.figure()
to make the figure window before you start plotting information to it
If you are using a GUI console such as Spyder, make sure you have turned on interactive plots so that it plots to a separate window and not inline into the console

Categories