iPython, Jupyter -> AttributeError: 'module' object has no attribute 'cbook' - python

I am a beginner at programming and I am working on an online course which uses ipython and jupyter notebook. I am working with Mac OS 10.13.3.
I have tried importing matplotlib as follows,
import matplotlib.pyplot as plt
%matplotlib inline
However, the following error is being generated.
--------------------------
Traceback (most recent call last) <ipython-input-30-385145dcc870> in <module>()
----> 1 import matplotlib.pyplot as plt
2 get_ipython().magic(u'matplotlib inline')
/Users/Varshil/anaconda/envs/gl-env/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
27 from cycler import cycler
28 import matplotlib
---> 29 import matplotlib.colorbar
30 from matplotlib import style
31 from matplotlib import _pylab_helpers, interactive
/Users/Varshil/anaconda/envs/gl-env/lib/python2.7/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
/Users/Varshil/anaconda/envs/gl-env/lib/python2.7/site-packages/matplotlib/artist.py in <module>()
9 import numpy as np
10 import matplotlib
---> 11 import matplotlib.cbook as cbook
12 from matplotlib.cbook import mplDeprecation
13 from matplotlib import docstring, rcParams
AttributeError: 'module' object has no attribute 'cbook'
It would be of great help if someone could help me solve this issue. I have tried looking up online but have found no successful leads.

This is because you are using old version of matplotlib.
Those who are using GraphLab Create, first activate virtual environment:
source gl-env/bin/activate
Now upgrade matplotlib:
pip install -U matplotlib
Output:
Found existing installation: matplotlib 1.5.1
Uninstalling matplotlib-1.5.1:
Successfully uninstalled matplotlib-1.5.1
Successfully installed matplotlib-2.1.2
Restart iPython/Jupyter.
If you are on Mac, you might get the following error:
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.
Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg
Again restart iPython/Jupyter.

Related

When I try to run "import matplotlib.pyplot as plt", I receive the following error: "ModuleNotFoundError: No module named 'PIL'"

EDIT: I noticed that this problem only occurs when I'm using Jupyter Notebook. When I tried to use Google Colab, it worked fine. Is there a way to resolve this issue?
I tried uninstalling and installing pillow, image, and even matplotlib, but I keep receiving the same error. Note that when I try to run "import image", "import pil" and "import matplotlib", they all worked fine.
This is the exact message:
ModuleNotFoundError Traceback (most recent call last)
in
5 import matplotlib.pyplot as plt
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in
34 from cycler import cycler
35 import matplotlib
36 import matplotlib.colorbar
37 import matplotlib.image
38 from matplotlib import rcsetup, style
~\Anaconda3\lib\site-packages\matplotlib\colorbar.py in
42 import matplotlib.collections as collections
43 import matplotlib.colors as colors
44 import matplotlib.contour as contour
45 import matplotlib.cm as cm
46 import matplotlib.gridspec as gridspec
~\Anaconda3\lib\site-packages\matplotlib\contour.py in
15 import matplotlib.collections as mcoll
16 import matplotlib.font_manager as font_manager
17 import matplotlib.text as text
18 import matplotlib.cbook as cbook
19 import matplotlib.mathtext as mathtext
~\Anaconda3\lib\site-packages\matplotlib\text.py in
14 from .font_manager import FontProperties
15 from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle
16 from .textpath import TextPath # Unused, but imported by others.
17 from .transforms import (
18 Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform)
~\Anaconda3\lib\site-packages\matplotlib\textpath.py in
9 from matplotlib.font_manager import FontProperties, get_font
10 from matplotlib.ft2font import LOAD_NO_HINTING, LOAD_TARGET_LIGHT
11 from matplotlib.mathtext import MathTextParser
12 from matplotlib.path import Path
13 from matplotlib.transforms import Affine2D
~\Anaconda3\lib\site-packages\matplotlib\mathtext.py in
25
26 import numpy as np
27 from PIL import Image
28 from pyparsing import (
29 Combine, Empty, FollowedBy, Forward, Group, Literal, oneOf, OneOrMore,
ModuleNotFoundError: No module named 'PIL'
I found that this issue only occurred when using Jupyter Notebook, so after several tries I uninstalled Anaconda and reinstalled it and now it works.
Try importing like this
import PIL as Image
It's import PIL not import pil. Normally you should also be able to see which line causes the error. There is nothing wrong with the matplotlib import that you mentioned.
First, install PIL through command line python -m pip install pillow.
Second, use it, do in your script from PIL import Image.

KeyError: 'scale' for import matplotlib.pyplot as plt

I'm getting KeyError: 'scale'
when I'm trying to run import matplotlib.pyplot
I redownloaded the matplotlib then ran the code but still getting the same error.
I've also opened the new Jupyter notebook and only ran "import matplotlib.pyplot as plt" and I'm still getting the same error. I didn't get any error when I ran "import matplotlib" only.
I would be grateful if you help me out find what's causing the error.
import matplotlib.pyplot as plt
%matplotlib inline
city_pay_top50.plot(kind='bar', x='customer_city', y='payment_value')
plt.title('Cities with top 50 revenues')
plt.show()
KeyError Traceback (most recent call last)
<ipython-input-6-07805b46bb32> in <module>
----> 1 import matplotlib.pyplot as plt
2 #%matplotlib inline
3
4 plt.bar(city_pay_top50['customer_city'], city_pay_top50['payment_value'])
5 #city_pay_top50.plot(kind='bar', x='customer_city', y='payment_value')
~/opt/anaconda3/lib/python3.7/site-packages/matplotlib-3.2.1+1847.gfc8a2fa24-py3.7-macosx-10.9-x86_64.egg/matplotlib/pyplot.py in <module>
41 from matplotlib import docstring
42 from matplotlib.backend_bases import FigureCanvasBase, MouseButton
---> 43 from matplotlib.figure import Figure, figaspect
44 from matplotlib.gridspec import GridSpec
45 from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
~/opt/anaconda3/lib/python3.7/site-packages/matplotlib-3.2.1+1847.gfc8a2fa24-py3.7-macosx-10.9-x86_64.egg/matplotlib/figure.py in <module>
15
16 import matplotlib as mpl
---> 17 from matplotlib import docstring, projections
18 from matplotlib import __version__ as _mpl_version
19
~/opt/anaconda3/lib/python3.7/site-packages/matplotlib-3.2.1+1847.gfc8a2fa24-py3.7-macosx-10.9-x86_64.egg/matplotlib/projections/__init__.py in <module>
2 from .geo import AitoffAxes, HammerAxes, LambertAxes, MollweideAxes
3 from .polar import PolarAxes
----> 4 from mpl_toolkits.mplot3d import Axes3D
5
6
~/opt/anaconda3/lib/python3.7/site-packages/mpl_toolkits/mplot3d/__init__.py in <module>
----> 1 from .axes3d import Axes3D
~/opt/anaconda3/lib/python3.7/site-packages/mpl_toolkits/mplot3d/axes3d.py in <module>
40
41
---> 42 class Axes3D(Axes):
43 """
44 3D axes object.
~/opt/anaconda3/lib/python3.7/site-packages/mpl_toolkits/mplot3d/axes3d.py in Axes3D()
50 def __init__(
51 self, fig, rect=None, *args,
---> 52 azim=-60, elev=30, zscale=None, sharez=None, proj_type='persp',
53 **kwargs):
54 """
~/opt/anaconda3/lib/python3.7/site-packages/matplotlib-3.2.1+1847.gfc8a2fa24-py3.7-macosx-10.9-x86_64.egg/matplotlib/docstring.py in dedent_interpd(func)
78 """Dedent *func*'s docstring, then interpolate it with ``interpd``."""
79 func.__doc__ = inspect.getdoc(func)
---> 80 return interpd(func)
~/opt/anaconda3/lib/python3.7/site-packages/matplotlib-3.2.1+1847.gfc8a2fa24-py3.7-macosx-10.9-x86_64.egg/matplotlib/docstring.py in __call__(self, func)
38 def __call__(self, func):
39 if func.__doc__:
---> 40 func.__doc__ %= self.params
41 return func
42
KeyError: 'scale'
For those who may face the same error as me, the problem was solved by updating the version of Jupyter notebook to the latest version in my case.
It appears to be related to a version mismatch between mpl_toolkits and matplotlib. I couldn’t figure out how to upgrade mpl_toolkits, so I downgraded matplotlib, and the error went away.
pip3 install matplotlib==2.*
I had the same problem. In my case this issue was solved by remove mpl-toolkits in appdata
~/opt/anaconda3/lib/python3.7/site-packages/mpl_toolkits/
It will be helpful remove this file
Uninstall the old Matplotlib first using the command:
sudo pip3 uninstall matplotlib
Install it again using:
sudo pip3 install matplotlib
Check whether it is working or not. If not working Uninstall twice the matplotlib. Because two version matplotlib may present.
Like this method only, I solved the issue or update the anaconda to update the new version If you are using anaconda.
Hope this may work well.
I met with this problem, too. And the problem is solved by
conda install matplotlib
Hope this working.
In my case, using ipython and matplotlib installed in virtualenv, I had to install python-tk on my Ubuntu 20.04:
sudo apt install python-tk
based on:
https://matplotlib.org/3.1.1/faq/virtualenv_faq.html
I had to pip3 uninstall matplotlib twice since I apparently had 2 versions installed. Then reinstall it.

I am facing this issue in seaborn import:

When I try running following line in Jupiter notebook
> import seaborn as sns
I get this error:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-2-ed9806ce3570> in <module>()
----> 1 import seaborn as sns
~/anaconda3/lib/python3.6/site-packages/seaborn/__init__.py in <module>()
8 from .palettes import *
9 from .regression import *
---> 10 from .categorical import *
11 from .distributions import *
12 from .timeseries import *
~/anaconda3/lib/python3.6/site-packages/seaborn/categorical.py in <module>()
5 from scipy import stats
6 import pandas as pd
----> 7 from pandas.core.series import remove_na
8 import matplotlib as mpl
9 from matplotlib.collections import PatchCollection
ImportError: cannot import name 'remove_na'
dependency versions are listed below:
Python 3.6.3
conda 4.8.2
numpy 1.18.0
pandas 1.0.1
scipy 1.1.0
matplotlib 3.1.3
What is the issue here?
Okay,
so I still dont know, what was wrong in this, but I did solve the problem.
I simply uninstalled seaborn
pip3 uninstall seaborn
and installed it again
pip3 install seaborn
it worked, no error this time.
But I still dont know, what went wrong first time.
If someone can help please share.
The problem is that seaborn seems to be using a private method from pandas. The issue has been reported to both pandas and seaborn developers (see https://github.com/pandas-dev/pandas/issues/16971 and https://github.com/mwaskom/seaborn/pull/1241) which both published a fix in later versions.
The fixed version is available on pip but not on Ubuntu's packages yet (as of August 2020).
However, for those who don't want pip install, the fix is straightforward and can be manually applied (see the pull request above).

cannot import name 'ft2font' from 'matplotlib' on windows10

I am using a windows10 machine and using PyCharm as my IDE, so when I tried to run the below code, it shows the following error
I tried uninstalling and re-installing matplotlib and also as someone from SO suggested used --force reinstall too, but didn't work
It was working well until yesterday
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.RandomState(42)
X = 10 * rng.rand(50)
y = 2 * X - 1 + rng.randn(50)
plt.scatter(X, y)
plt.show()
Error showing on both Pycharm and Vs Code
Traceback (most recent call last):
File "D:/PyCharm/exercise/numpy_exercise/pandas_py.py", line 1, in
<module>
import matplotlib.pyplot as plt
File "C:\Users\smile\AppData\Roaming\Python\Python37\site-
packages\matplotlib\__init__.py", line 143, in <module>
from matplotlib import ft2font
ImportError: cannot import name 'ft2font' from 'matplotlib'
(C:\Users\smile\AppData\Roaming\Python\Python37\site-
packages\matplotlib\__init__.py)
Error showing on Jupyter Notebook
<ipython-input-1-1842680e3d86> in <module>
1 import pandas as pd
2 import numpy as np
----> 3 import matplotlib.pyplot as plt
4 get_ipython().run_line_magic('matplotlib', 'inline')
5
~\AppData\Roaming\Python\Python37\site-packages\matplotlib\pyplot.py in
<module>
30 from cycler import cycler
31 import matplotlib
---> 32 import matplotlib.colorbar
33 import matplotlib.image
34 from matplotlib import rcsetup, style
~\AppData\Roaming\Python\Python37\site-packages\matplotlib\colorbar.py
in <module>
25
26 import matplotlib as mpl
---> 27 import matplotlib.artist as martist
28 import matplotlib.cbook as cbook
29 import matplotlib.collections as collections
ModuleNotFoundError: No module named 'matplotlib.artist'
I had a similar problem which was solved simply by forcing the reinstall of matplotlib:
python -m pip install -I matplotlib
The python -m pip instead of pip install to make sure the correct python executable is used
The -I forces reinstall
I believe i had a similar issue - https://github.com/matplotlib/jupyter-matplotlib/issues/155 - It could be that you are using python installed from a different source (appstore or from python.org?). I suspect the issue is that your kernel is using a different python than it was a few days ago.
try deleting the Python folder in:
Users\smile\AppData\Roaming\Python\Python37\site-packages\matplotlib__init__.py)
and run again.

Installing matplotlib via pip on Ubuntu 12.04

I'm trying to use matplotlib on Ubuntu 12.04. So I built a wheel with pip:
python .local/bin/pip wheel --wheel-dir=wheel/ --build=build/ matplotlib
Then successfully installed it:
python .local/bin/pip install --user --no-index --find-links=wheel/ --build=build/ matplotlib
But when I'm trying to import it in ipython ImportError occures:
In [1]: import matplotlib
In [2]: matplotlib.get_backend()
Out[2]: u'agg'
In [3]: import matplotlib.pyplot
ImportError
Traceback (most recent call
last) /place/home/yefremat/ in
()
----> 1 import matplotlib.pyplot
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/pyplot.py
in ()
32 from matplotlib import docstring
33 from matplotlib.backend_bases import FigureCanvasBase
---> 34 from matplotlib.figure import Figure, figaspect
35 from matplotlib.gridspec import GridSpec
36 from matplotlib.image import imread as _imread
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/figure.py
in ()
38 import matplotlib.colorbar as cbar
39
---> 40 from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
41 from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
42 from matplotlib.legend import Legend
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/axes/init.py
in ()
2 unicode_literals)
3
----> 4 from ._subplots import *
5 from ._axes import *
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/axes/_subplots.py
in ()
8 from matplotlib import docstring
9 import matplotlib.artist as martist
---> 10 from matplotlib.axes._axes import Axes
11
12 import warnings
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/axes/_axes.py
in ()
36 import matplotlib.ticker as mticker
37 import matplotlib.transforms as mtransforms
---> 38 import matplotlib.tri as mtri
39 import matplotlib.transforms as mtrans
40 from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/tri/init.py
in ()
7 import six
8
----> 9 from .triangulation import *
10 from .tricontour import *
11 from .tritools import *
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/tri/triangulation.py
in ()
4 import six
5
----> 6 import matplotlib._tri as _tri
7 import matplotlib._qhull as _qhull
8 import numpy as np
ImportError:
/home/yefremat/.local/lib/python2.7/site-packages/matplotlib/_tri.so:
undefined symbol: _ZNSt8__detail15_List_node_base9_M_unhookEv
May be I'm doing somethig wrong? Or may be there is a way to turn off gui support of matplotlib?
Thanks in advance.
Okay, the problem was in gcc version. During building and creating wheel of package pip uses system gcc (which version is 4.7.2). I'm using python from virtualenv, which was built with gcc 4.4.3. So version of libstdc++ library is different in IPython and one that pip used.
As always there are two solutions (or even more): pass LD_PRELOAD environment variable with correct libstdc++ before entering IPython or to use same version of gcc during creating wheel and building virtualenv. I prefred the last one.
Thank you all.

Categories

Resources