figsize does not work for matplotlib 3d plot - python

I plotted 2 figures, here is the screenshot
figsize
the one (2D) on top is rendered as expected.
the one (3D) on bottom is not, the figure is so small!
setting the value of figsize does not work.
figsize=(3,3) and figsize=(13,13) give the same result!
%matplotlib inline rendered same way.
I tried different browsers, clear the cache, dose not work either.
I guess some rcParams control this, because this is reproducible only on my mac, but I don't have a clue to find it!
any clue will be appreciated.
whole coding:
%pylab inline
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(3,3))
ax = fig.gca(projection='3d')
ax.scatter(0.5, 0.5, 0.5, marker = '^')

As of notebook version 5.7.4, on MacOS 10.14.2 and Chrome 71.0.3578.98, this problem persists but can be fixed with %matplotlib inline setting by using the magic command
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
as given in the documentation here.
Correctly funcitoning example.

It appears to be a bug in Jupyter.
As a quick fix, you can use the notebook- instead of the inline-backend for matplotlib.
To do so, replace %matplotlib inline with %matplotlib notebook.

Upgrading matplotlib from version 3.0.0 to 3.0.2 solved the problem. If you use pip type:
pip install --upgrade matplotlib
I verified the case with Jupyter version 4.4.0.

Related

Not possible to see the plot created in Jupyter notebooks when using magic: %matplotlib notebook. Windows 10 and Chrome

Hi everyone. I am running jupyter notebook through Chrome and Windows
10. the versions are : Windows 10 Chrome Version 84.0.4147.105 (Official Build) (64-bit) I am using the magic %matplotlib notebook.
To be able to zoom in and out in the plot. The code works in other
machines with same windows and version. However, when I run it in my
personal laptop, the plot is not possible to see it:
I was trying to follow the following info found: help
I have run out of ideas, I restarted the laptop, reinstalled jupyter,
and nothing seems to work. Did anyone have a similar issue? Here is the code:
%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import numpy as np
import pandas as pd
def g(qi,d):
fig = plt.figure()
x_1 = df['dprod_year']
y_1 = qi*np.exp(-x_1*d)
plt.scatter(x_1,y_1,marker='+')
plt.scatter(df['dprod_year'],df['qoil_1000b'],marker='o',color='grey')
plt.ylim(0,4000)
plt.xlim(0,60)
plt.grid(True,axis='both')
"""
#interact(g,qi=(0.0000,5000,10),d=(0.0000,0.02000,0.0010))
"""
interact(g,qi=widgets.FloatSlider(value=3900,min=0,max=4000,step=10,description='qi:',readout_format='.1f'),
d=widgets.FloatSlider(value=0.0061,min=0.0001,max=0.01,step=0.001,description='d:',readout_format='.5f'))
plt.show()
Thank you very much for your help.
You should try to change from %matplotlib notebook to %matplotlib inline.
If that doesn't work then try to restart the kernel.
It seems that in some cases it helps to repeat the setting of the notebook backend, i.e. try calling it twice like
%matplotlib notebook
%matplotlib notebook
An analysis for why that is can be found in this comment

%matplotlib qt5 runs but doesn't generate graphs

I was using this code on my Jupyter Notebook until yesterday and it was working fine:
%matplotlib qt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X,Y,Z,c='black')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
This morning, for no apparent reason, it started saying that there was an error with qt4 or something. After some research I installed qt5 and changed the first line of the code to "%matplotlib qt5" which now makes the code run without errors, but doesn't generate any graphs. If I take the 5 after qt I run into the message "Warning: Cannot change to a different GUI toolkit: qt. Using qt5 instead.". I can still plot graphs with "%matplotlib inline", but I wanted some interactivity. Any ideas why this is happening?
It seems something got updated; but with the information available it's not possible to find out what it is. In any case, since you have pyqt5 installed you may use %matplotlib qt5. Then you probably just forgot to type plt.show()?
%matplotlib qt5
import matplotlib.pyplot as plt
plt.plot([1,4,2])
plt.show()
Also make sure to restart the kernel if you change the interactive backend, and if in doubt, let the line %matplotlib qt5 appear before importing pyplot.

%matplotlib notebook showing a blank histogram

In my Jupyter notebook I am now using %matplotlib notebook instead of %matplotlib inline, it's awesome that I can now interact with my plots on Jupyter. However, when I try to make an histogram I get a blank plot:
If I use %matplotlib inline everything works fine:
What's going on?
Seeing that my comment above has indeed helped someone to solve the problem I will post it as an answer.
The problem occurs if you switch from %matplotlib inline to %matplotlib notebook without restarting the kernel.
Switching from %matplotlib notebook to %matplotlib inline works fine.
So the solution is to either restart the kernel or start a new notebook.
It seems that in some cases it helps to repeat the setting of the notebook backend, i.e. call it twice like
%matplotlib notebook
%matplotlib notebook
An analysis for why that is can be found in this comment
The answer is not necessarily to restart the entire kernel.
If you reload the matplotlib module, it will work, too. Provided you use Python 3.6 like me, and you have import matplotlib.pyplot as plt like me:
from importlib import reload
reload(plt)
%matplotlib notebook
It does the trick. Yes it is still a hack. At least this is an independent codecell you can use in the middle of the notebook. Switching back via %matplotlib inline is not a problem.
You can also remove once imported names from the sys.modules list, then they get imported again when you call the import again.
import sys
sys.modules.pop('matplotlib')
from matplotlib import pyplot as plt
In many cases, that's a less good idea. But it might sometimes be the only straw to hold on.
I was able to fix it by downgrading matplotlib to 3.1.3:
conda install matplotlib=3.1.3
I was running version 3.3.2 and had this same issue. I was not switching between %matplotlib inline and %matplotlib notebook, and it did not matter if I placed %matplotlib notebook before or after importing
The issue seems to be an interaction between switching:
%matplotlib notebook
%matplotlib inline
and using the figure "power button" on interactive plots:
Solution: If you pressed the button and are getting blank plots, restart Jupyter and don't use the power button again if you need to switch between notebook and inline
On a new notebook if you start by using %matplotlib notebook then you can switch between that an inline without issue.
I confirm that both restarting of the kernel and the running of the code do the trick!
For me, it also appeared after switching from 'inline' to 'notebook' but restarting the kernel didn't work. I had to go through file > close and halt, and then either reopen it or restart the kernel if the page is still open.

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

Plotting window doesn't show up with pylab [duplicate]

I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
I get no plot window. Any ideas on how to get the plot window to show?
You can type
import pylab
pylab.show()
or better, use ipython -pylab.
Since the use of pylab is not recommended anymore, the solution would nowadays be
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show()
pylab.show() works but blocks (you need to close the window).
A much more convenient solution is to do pylab.ion() (interactive mode on) when you start: all (the pylab equivalents of) pyplot.* commands display their plot immediately. More information on the interactive mode can be found on the official web site.
I also second using the even more convenient ipython -pylab (--pylab, in newer versions), which allows you to skip the from … import … part (%pylab works, too, in newer IPython versions).
Try this:
import matplotlib
matplotlib.use('TkAgg')
BEFORE import pylab
The code snippet below works on both Eclipse and the Python shell:
import numpy as np
import matplotlib.pyplot as plt
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Just print x and y for fun
print x
print y
# 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
plt.show()
Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (.matplotlib/matplotlibrc) in you home directory.
To set the backend in code you can do
import matplotlib
matplotlib.use('Agg')
where 'Agg' is the name of the backend. Which backends are present depend on your installation and OS.
http://matplotlib.sourceforge.net/faq/installing_faq.html#backends
http://matplotlib.org/users/customizing.html
Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.
Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.
If you are starting IPython with the --pylab option, you shouldn't need to call show() or draw(). Try this:
ipython --pylab=inline
--pylab no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py file to get both pylab as well as autoreload functionalities.
c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']
If you are user of Anaconda and Spyder then best solution for you is that :
Tools
-->
Preferences
-->
Ipython console
-->
Graphic Section
Then in the Support for graphics (Matplotlib) section:
select two avaliable options
and in the Graphics Backend:
select Automatic
Another possibility when using easy_install is that you need to require the most recent version of matplotlib.
Try:
import pkg_resources
pkg_resources.require("matplotlib")
before you import matplotlib or any of its modules.

Categories