Importing pyplot in a Jupyter Notebook - python

Running Python 2.7 and trying to get plotting to work the tutorials recommend the below command.
from matplotlib import pyplot as plt
Works fine when run from the command line
python -c "from matplotlib import pyplot as plt"
but I get an error when trying to run it inside a Jupyter Notebook.
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-21-1d1446f6fa64> in <module>()
----> 1 from matplotlib import pyplot as plt
/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py in <module>()
112
113 from matplotlib.backends import pylab_setup
--> 114 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
115
116 _IP_REGISTERED = None
/usr/local/lib/python2.7/dist-packages/matplotlib/backends/__init__.pyc in pylab_setup()
30 # imports. 0 means only perform absolute imports.
31 backend_mod = __import__(backend_name,
---> 32 globals(),locals(),[backend_name],0)
33
34 # Things we pull in from all backends
/usr/local/lib/python2.7/dist-packages/ipykernel/pylab/backend_inline.py in <module>()
154 configure_inline_support(ip, backend)
155
--> 156 _enable_matplotlib_integration()
/usr/local/lib/python2.7/dist-packages/ipykernel/pylab/backend_inline.py in _enable_matplotlib_integration()
152 backend = get_backend()
153 if ip and backend == 'module://%s' % __name__:
--> 154 configure_inline_support(ip, backend)
155
156 _enable_matplotlib_integration()
/usr/local/lib/python2.7/dist-packages/IPython/core/pylabtools.pyc in configure_inline_support(shell, backend)
359 except ImportError:
360 return
--> 361 from matplotlib import pyplot
362
363 cfg = InlineBackend.instance(parent=shell)
ImportError: cannot import name pyplot
The following command works
import matplotlib
But the following gives me a similar error
import matplotlib.pyplot

You can also use the %matplotlib inline magic, but it has to be preceded by the pure %matplotlib line:
Works (figures in new window)
%matplotlib
import matplotlib.pyplot as plt
Works (inline figures)
%matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
Does not work
%matplotlib inline
import matplotlib.pyplot as plt
Also: Failure to import matplotlib.pyplot in jupyter (but not ipython) seems to be the same issue. It looks like a recently introduced bug in the ipykernel. Maybe someone mark this or the other question as duplicate, thx.

Related

ImportError: cannot import name '_docstring' from partially initialized module 'matplotlib' (most likely due to a circular import)

I am trying to import matplotlib in .ipynb file but its not working, none of my files have the same name as _docstring yet I get this error and if I try something in .py file, it works fine.
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
I'm running this in a .ipynb file in VS Code
Output :
ImportError Traceback (most recent call last)
Cell In[3], line 2
1 import numpy as np
----> 2 import matplotlib.pyplot as plt
3 import cv2 as cv
File c:\Users\P****\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\__init__.py:113
109 from packaging.version import parse as parse_version
111 # cbook must import matplotlib only within function
112 # definitions, so it is safe to import from it here.
--> 113 from . import _api, _version, cbook, _docstring, rcsetup
114 from matplotlib.cbook import sanitize_sequence
115 from matplotlib._api import MatplotlibDeprecationWarning
ImportError: cannot import name '_docstring' from partially initialized module 'matplotlib' (most likely due to a circular import) (c:\Users\P****\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\__init__.py)
But if I try to import matplotlib in .py file like
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1,10,0.1)
y = x**2
plt.plot(x,y)
plt.show()
It runs fine, no issues.
Try deleting matplotlib folder and reinstalling it.
Full path: AppData\Roaming\Python\Python39\site-packages\matplotlib
It worked for me.

Need help dealing with a DLL error based on matplotlib.pyplot

Here is my basic program I am running with a local jupyter notebook on my computer. I am not sure how to resolve this dll error:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
Here is the error message accompanying my code:
ImportError Traceback (most recent call last)
<ipython-input-1-c1680853bc3a> in <module>()
1 import numpy as np
2 import matplotlib as mpl
----> 3 import matplotlib.pyplot as plt
4 #%matplotlib inline
c:\python27\lib\site-packages\matplotlib\pyplot.py in <module>()
29 from cycler import cycler
30 import matplotlib
---> 31 import matplotlib.colorbar
32 from matplotlib import style
33 from matplotlib import _pylab_helpers, interactive
c:\python27\lib\site-packages\matplotlib\colorbar.py in <module>()
30
31 import matplotlib as mpl
---> 32 import matplotlib.artist as martist
33 import matplotlib.cbook as cbook
34 import matplotlib.collections as collections
c:\python27\lib\site-packages\matplotlib\artist.py in <module>()
14 import matplotlib
15 from . import cbook, docstring, rcParams
---> 16 from .path import Path
17 from .transforms import (Bbox, IdentityTransform, Transform, TransformedBbox,
18 TransformedPatchPath, TransformedPath)
c:\python27\lib\site-packages\matplotlib\path.py in <module>()
19 import numpy as np
20
---> 21 from . import _path, rcParams
22 from .cbook import (_to_unmasked_float_array, simple_linear_interpolation,
23 maxdict)
ImportError: DLL load failed: %1 is not a valid Win32 application.

Cannot import matplotlib with ipython/jupyter notebook

Cannot import matplotlib with ipython/jupyter notebook through a virtual environment.
I'm able to import matplotlib just fine using the console. Having seen other SO posts I can't seem to get this set up right.
I followed this to get the separate ipython/jupyter kernel.
When I checked my locations through jupyter I get
six.__file__: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six.pyc'
and
datutil.__file__: '/Library/Python/2.7/site-packages/dateutil/__init__.pyc'
I am not sure these are correct. Main jupyter error below
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-3-20188fbdb2fd> in <module>()
1
----> 2 import matplotlib.pyplot as plt
3 get_ipython().magic(u'matplotlib inline')
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py in <module>()
27 from matplotlib import docstring
28 from matplotlib.backend_bases import FigureCanvasBase
---> 29 from matplotlib.figure import Figure, figaspect
30 from matplotlib.gridspec import GridSpec
31 from matplotlib.image import imread as _imread
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.py in <module>()
34 import matplotlib.colorbar as cbar
35
---> 36 from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
37 from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
38 from matplotlib.legend import Legend
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py in <module>()
18 import matplotlib.colors as mcolors
19 import matplotlib.contour as mcontour
---> 20 import matplotlib.dates as _ # <-registers a date unit converter
21 from matplotlib import docstring
22 import matplotlib.font_manager as font_manager
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/dates.py in <module>()
117
118
--> 119 from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
120 MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
121 SECONDLY)
/Library/Python/2.7/site-packages/dateutil/rrule.py in <module>()
17
18 from six import advance_iterator, integer_types
---> 19 from six.moves import _thread
20 import heapq
21
ImportError: cannot import name _thread
Ok I fixed this by using the tutorial properly (http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs)
You need to set up a virtualenv, then make sure that you install jupyter within it. I was using the globally installed jupyter.
Then set up the new jupyter kernel (linked above) and everything should work with your virtualenv pointed to correctly

ImportError: libpng16.so.16: cannot open shared object file: No such file or directory

Although this has come up as a topic before it has not been answered. I get the following import error I have just installed canopy from EPD and after I installed it, it keeps coming up with the following error:
IPython 2.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[TerminalIPythonApp] WARNING | Eventloop or matplotlib integration failed. Is matplotlib installed?
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/IPython/core/shellapp.pyc in <lambda>(key)
231 shell = self.shell
232 if self.pylab:
--> 233 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
234 key = self.pylab
235 elif self.matplotlib:
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in enable_pylab(self, gui, import_all, welcome_message)
2980 from IPython.core.pylabtools import import_pylab
2981
-> 2982 gui, backend = self.enable_matplotlib(gui)
2983
2984 # We want to prevent the loading of pylab to pollute the user's
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in enable_matplotlib(self, gui)
2941 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2942
-> 2943 pt.activate_matplotlib(backend)
2944 pt.configure_inline_support(self, backend)
2945
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in activate_matplotlib(backend)
285 matplotlib.rcParams['backend'] = backend
286
--> 287 import matplotlib.pyplot
288 matplotlib.pyplot.switch_backend(backend)
289
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
22
23 import matplotlib
---> 24 import matplotlib.colorbar
25 from matplotlib import _pylab_helpers, interactive
26 from matplotlib.cbook import dedent, silent_list, is_string_like, is_numlike
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/matplotlib/colorbar.py in <module>()
27 import matplotlib.artist as martist
28 import matplotlib.cbook as cbook
---> 29 import matplotlib.collections as collections
30 import matplotlib.colors as colors
31 import matplotlib.contour as contour
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/matplotlib/collections.py in <module>()
21 import matplotlib.artist as artist
22 from matplotlib.artist import allow_rasterization
---> 23 import matplotlib.backend_bases as backend_bases
24 import matplotlib.path as mpath
25 from matplotlib import _path
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/matplotlib/backend_bases.py in <module>()
48
49 import matplotlib.tight_bbox as tight_bbox
---> 50 import matplotlib.textpath as textpath
51 from matplotlib.path import Path
52 from matplotlib.cbook import mplDeprecation
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/matplotlib/textpath.py in <module>()
9 from matplotlib.path import Path
10 from matplotlib import rcParams
---> 11 import matplotlib.font_manager as font_manager
12 from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, LOAD_NO_HINTING
13 from matplotlib.ft2font import LOAD_TARGET_LIGHT
/home/rhys/Documents/Uni_work/Year_2_research_placement/User/lib/python2.7/site-packages/matplotlib/font_manager.py in <module>()
51 import matplotlib
52 from matplotlib import afm
---> 53 from matplotlib import ft2font
54 from matplotlib import rcParams, get_cachedir
55 from matplotlib.cbook import is_string_like
ImportError: libpng16.so.16: cannot open shared object file: No such file or directory
I have tried reinstalling matplotlib but it still comes up with the error and I cannot find the libpng16.so.16 file in \usr\local\lib, can anyone help?
Check Canopy's Package Manager. Make sure matplotlib 1.3.1-8 package is installed.
An older version of matplotlib could be installed. Check the updates section and update your canopy.

Ipython notebook. %pylab load error in Windows 7

I run Windows 7, Enthought Python Distribution 7.3-2 Academic.
I open a command prompt, change to my code directory and type
U:\rsch>ipython notebook
In a new notebook, I type %pylab and receive the following error:
In [1]: %pylab
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
U:\rsch\<ipython-input-1-5c1faa999e5b> in <module>()
----> 1 get_ipython().magic(u'pylab')
D:\Python27\lib\site-packages\IPython\core\interactiveshell.pyc in magic(self, arg_s, next_input)
1983 self._magic_locals = sys._getframe(1).f_locals
1984 with self.builtin_trap:
-> 1985 result = fn(magic_args)
1986 # Ensure we're not keeping object references around:
1987 self._magic_locals = {}
D:\Python27\lib\site-packages\IPython\core\magic.pyc in magic_pylab(self, s)
3471 import_all_status = True
3472
-> 3473 self.shell.enable_pylab(s, import_all=import_all_status)
3474
3475 def magic_tb(self, s):
D:\Python27\lib\site-packages\IPython\core\interactiveshell.pyc in enable_pylab(self, gui, import_all)
2592 ns = {}
2593 try:
-> 2594 gui = pylab_activate(ns, gui, import_all, self)
2595 except KeyError:
2596 error("Backend %r not supported" % gui)
D:\Python27\lib\site-packages\IPython\core\pylabtools.pyc in pylab_activate(user_ns, gui, import_all, shell)
327 itself, and will be needed next to configure IPython's gui integration.
328 """
--> 329 gui, backend = find_gui_and_backend(gui)
330 activate_matplotlib(backend)
331 import_pylab(user_ns, import_all)
D:\Python27\lib\site-packages\IPython\core\pylabtools.pyc in find_gui_and_backend(gui)
194 """
195
--> 196 import matplotlib
197
198 if gui and gui != 'auto':
D:\Python27\lib\site-packages\matplotlib\__init__.py in <module>()
131 import sys, os, tempfile
132
--> 133 from matplotlib.rcsetup import (defaultParams,
134 validate_backend,
135 validate_toolbar,
D:\Python27\lib\site-packages\matplotlib\rcsetup.py in <module>()
17 import warnings
18 from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
---> 19 from matplotlib.colors import is_color_like
20
21 #interactive_bk = ['gtk', 'gtkagg', 'gtkcairo', 'fltkagg', 'qtagg', 'qt4agg',
D:\Python27\lib\site-packages\matplotlib\colors.py in <module>()
50 """
51 import re
---> 52 import numpy as np
53 from numpy import ma
54 import matplotlib.cbook as cbook
D:\Python27\lib\site-packages\numpy\__init__.pyc in <module>()
141 return loader(*packages, **options)
142
--> 143 import add_newdocs
144 __all__ = ['add_newdocs']
145
D:\Python27\lib\site-packages\numpy\add_newdocs.py in <module>()
7 # core/fromnumeric.py, core/defmatrix.py up-to-date.
8
----> 9 from numpy.lib import add_newdoc
10
11 ###############################################################################
D:\Python27\lib\site-packages\numpy\lib\__init__.py in <module>()
11
12 import scimath as emath
---> 13 from polynomial import *
14 #import convertcode
15 from utils import *
D:\Python27\lib\site-packages\numpy\lib\polynomial.py in <module>()
15 from numpy.lib.function_base import trim_zeros, sort_complex
16 from numpy.lib.type_check import iscomplex, real, imag
---> 17 from numpy.linalg import eigvals, lstsq
18
19 class RankWarning(UserWarning):
D:\Python27\lib\site-packages\numpy\linalg\__init__.py in <module>()
46 from info import __doc__
47
---> 48 from linalg import *
49
50 from numpy.testing import Tester
D:\Python27\lib\site-packages\numpy\linalg\linalg.py in <module>()
21 isfinite, size, finfo, absolute, log, exp
22 from numpy.lib import triu
---> 23 from numpy.linalg import lapack_lite
24 from numpy.matrixlib.defmatrix import matrix_power
25 from numpy.compat import asbytes
ImportError: DLL load failed: The specified path is invalid.
Not sure what to do. Thanks.
I experienced the same problem and here is what worked for me:
I made sure I call the IPython without "pylab"
I then made sure all sessions/instances (excuse me but I'm new to this :) are closed. You can do this by ctrl-C in all Terminals and in the Notebook dashboard press "shutdown" if possible.
There are probably more elegant ways to do this but this is what worked for me.
Developers, take note that many newbies might get very frustrated when the first notebook they try to run gives them an error.
Adam
It's likely that you're missing the Scripts directory in your system path. To check, run
echo %PATH%
from the command prompt and look for D:\Python27\Scripts. If it's missing, you can add it manually from the Control Panel, or using a utility like Rapid Environment Editor.
EPD shipped with ipython 0.12. Ipython has developed a lot since then. You should update to ipython 0.13.1 by entering "enpkg ipython", as described in more detail here:
https://support.enthought.com/entries/22415022-Using-enpkg-to-update-EPD-packages
Unfortunately these error messages arent really useful. From the message you only know that 'some dll' fails to import during the import of "lapack_lite" (part of Numpy).
You can use Dependency Walker to see which specific DLL is causing the problem, opening "D:\Python27\Lib\site-packages\numpy\linalg\lapack_lite.pyd" might reveal some more information.

Categories

Resources