AttributeError: 'module' object has no attribute 'cbook' - python

I am trying to run a simple code and I have all the dependencies for matplotlib and numpy installed in my Canopy. Still I am getting error.
import cv2
import numpy as np
import matplotlib.pyplot as plt
x = cv2.imread('jay.jpg')
plt.imshow(x, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
Error:
%run "c:\users\jay\appdata\local\temp\tmppvibq9.py"
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
c:\users\jay\appdata\local\temp\tmppvibq9.py in <module>()
2 import numpy as np
3 import matplotlib.cbook
----> 4 import matplotlib.pyplot as plt
5
6 x = cv2.imread('jay.jpg')
C:\Users\Jay\AppData\Local\Enthought\Canopy\System\Lib\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
C:\Users\Jay\AppData\Local\Enthought\Canopy\System\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:\Users\Jay\AppData\Local\Enthought\Canopy\System\Lib\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'
Dependencies I have installed for numpy and matplotlib:
1.) libsvm-3.17.win64-py2.7
2.) pyparsing-2.0.3-1.win64-py2.7
3.) python-dateutil-2.4.2-2.win64-py2.7
4.) pytz-2015.7-1.win64-py2.7
5.) six-1.10.0-1.win64-py2.7
6.) scipy-0.13.3.win64-py2.7
7.) numpy-MKL-1.9.2-2.win64-py2.7
8.) Matplotlib 1.5.1-win64-py2.7
9.) pip 8.0.2-1.win64-py2.7

Try this:
Close your jupyter notebook and terminate ipython.
Restart Terminal
Enter this command in Terminal:
export LANG=en_US.UTF-8;export LC_ALL=en_US.UTF-8
Re-run your ipython / Jupyter notebook now. It works like a charm.

conda install matplotlib --force

I don't know for sure that this is causing your problem, but you are running your code in the wrong Python environment:
C:\Users\Jay\AppData\Local\Enthought\Canopy\System\
You should be running it in
C:\Users\Jay\AppData\Local\Enthought\Canopy\User
See
https://support.enthought.com/entries/23646538-Make-Canopy-User-Python-be-your-default-Python
and
http://docs.enthought.com/canopy/configure/faq.html#where-are-all-of-the-python-packages-in-my-user-python-environment

You can find which 'matplotlib.py' is imported and then open that file and check if it has 'cbook' or not.
import imp
imp.find_module("matplotlib")

i had the same problem and it was because of this line :
from sys import stdout
i deleted this import and the problem is gone now

Related

No module named 'sklearn.neighbors.base' still existed after all the suggestions what I can take

I learned a lot of solutions from this website, but still cannot solve the problem. My code is as follows for your review:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
import altair as alt
from statsmodels.graphics.mosaicplot import mosaic
from scipy.stats import chi2_contingency
import plotly.express as px
from pandas.plotting import parallel_coordinates
from wordcloud import WordCloud
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
from scipy.spatial import distance
!pip install sklearn
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
from missingpy import MissForest
import sklearn.neighbors._base
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
import warnings
warnings.filterwarnings("ignore")
And still shows the error: ModuleNotFoundError: No module named 'sklearn.neighbors.base' I've tried to do the follows:
pip install -U imbalanced-learn ;
pip install -U scikit-learn
ans there was still of no use
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11280/2643854484.py in <module>
26 from sklearn.impute import IterativeImputer
27 from sklearn.impute import KNNImputer
---> 28 from missingpy import MissForest
29 import sklearn.neighbors._base
30 sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
C:\ProgramData\Anaconda3\lib\site-packages\missingpy\__init__.py in <module>
----> 1 from .knnimpute import KNNImputer
2 from .missforest import MissForest
3
4 __all__ = ['KNNImputer', 'MissForest']
C:\ProgramData\Anaconda3\lib\site-packages\missingpy\knnimpute.py in <module>
11 from sklearn.utils.validation import check_is_fitted
12 from sklearn.utils.validation import FLOAT_DTYPES
---> 13 from sklearn.neighbors.base import _check_weights
14 from sklearn.neighbors.base import _get_weights
15
ModuleNotFoundError: No module named 'sklearn.neighbors.base'
Finally, I solved the problem!!
I should write this before import missingpy, not behind it.
import sklearn.neighbors._base
import sys
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
from missingpy import MissForest
done.

'geopandas' has no attribute 'plotting' --- Problem in importing geopandas

Okay, so I am currently working on a project using Jupyter Notebook and had to create colormaped representations of USA counties, thus I realised that I need to install geopandas to proceed further.
So, on the mac terminal I wrote
pip install geopandas
and it installed v 0.10.2 for me.
But now when I am doing the following:
import geopandas
in notebook, it gives me this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-90-2ba400db65f5> in <module>
23 import xlrd
24 import plotly.figure_factory as ff
---> 25 import geopandas.plotting
~/opt/anaconda3/lib/python3.8/site-packages/geopandas/__init__.py in <module>
2
3 from geopandas.geoseries import GeoSeries # noqa
----> 4 from geopandas.geodataframe import GeoDataFrame # noqa
5 from geopandas.array import points_from_xy # noqa
6
~/opt/anaconda3/lib/python3.8/site-packages/geopandas/geodataframe.py in <module>
62
63
---> 64 class GeoDataFrame(GeoPandasBase, DataFrame):
65 """
66 A GeoDataFrame object is a pandas.DataFrame that has a column
~/opt/anaconda3/lib/python3.8/site-packages/geopandas/geodataframe.py in GeoDataFrame()
1851 return self.geometry.difference(other)
1852
-> 1853 plot = CachedAccessor("plot", geopandas.plotting.GeoplotAccessor)
1854
1855 #doc(_explore)
AttributeError: partially initialized module 'geopandas' has no attribute 'plotting' (most likely due to a circular import)
The complete block of code which is getting executed is as follows:
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
import opendatasets as od
import plotly.express as px
import plotly.graph_objs as go
from plotly.offline import iplot
import seaborn as sns
import re
from plotly.offline import init_notebook_mode
init_notebook_mode(connected=True)
from wordcloud import WordCloud
from math import pi
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
from tqdm import tqdm
import shapely
import shapefile
import xlrd
import plotly.figure_factory as ff
import geopandas
Kindly explain how can I solve this error and proceed further. I have tried all from my side for couple of hours.
What exactly is this 'most likely due to a circular import'? How to resolve it?

Python 3.5 Windows cannot run Rodeo example?

I just installed Python 3.5 on windows 10 and was trying to run the startup example from the IDE I choose (Rodeo). The example gives an error when trying to import ggplot. Specifically, at this call
from ggplot import ggplot, aes, geom_bar
which gives me:
ImportErrorTraceback (most recent call last)
in ()
----> 1 from ggplot import ggplot, aes, geom_bar
C:\Anaconda3\lib\site-packages\ggplot\__init__.py in ()
17
18
---> 19 from .geoms import geom_area, geom_blank, geom_boxplot, geom_line, geom_point, geom_jitter, geom_histogram, geom_density, geom_hline, geom_vline, geom_bar, geom_abline, geom_tile, geom_rect, geom_bin2d, geom_step, geom_text, geom_path, geom_ribbon, geom_now_its_art, geom_violin, geom_errorbar, geom_polygon
20 from .stats import stat_smooth, stat_density
21
C:\Anaconda3\lib\site-packages\ggplot\geoms\__init__.py in ()
----> 1 from .geom_abline import geom_abline
2 from .geom_area import geom_area
3 from .geom_bar import geom_bar
4 from .geom_bin2d import geom_bin2d
5 from .geom_blank import geom_blank
C:\Anaconda3\lib\site-packages\ggplot\geoms\geom_abline.py in ()
----> 1 from .geom import geom
2
3 class geom_abline(geom):
4 """
5 Line specified by slope and intercept
C:\Anaconda3\lib\site-packages\ggplot\geoms\geom.py in ()
1 from __future__ import (absolute_import, division, print_function,
2 unicode_literals)
----> 3 from ..ggplot import ggplot
4 from ..aes import aes
5
C:\Anaconda3\lib\site-packages\ggplot\ggplot.py in ()
19 from . import discretemappers
20 from .utils import format_ticks
---> 21 import StringIO
22 import urllib
23 import base64
ImportError: No module named 'StringIO'
So StringIO cannot be imported. I read here that StringIO doens't exist in that form anymore, but the fixes over there did not help me out. Any tips? What might be relevant (although I cannot judge that) is that I'm unable to update Scipy or ggplot via pip install ggplot --upgrade, but I thought/ read somewhere that this happens because I do not have a built in compiler on my windows machine. Many thanks in advance!
Well, I found a solution myself. pip install ggplot --upgrade failed for me, but
conda install -c conda-forge ggplot did the trick.

Cannot run matplotlib with Apache Zeppelin

I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it?
%pyspark
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
And here is the error I've got
Traceback (most recent call last):
File "/tmp/zeppelin_pyspark-3580576524078731606.py", line 235, in <module>
eval(compiledCode)
File "<string>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/matplotlib/pyplot.py", line 78, in <module>
new_figure_manager, draw_if_interactive, show = pylab_setup()
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 8, in <module>
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
_init()
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
I also try to add these lines, but still cannot work
import matplotlib
matplotlib.use('Agg')
The following works for me with Spark & Python 3:
%pyspark
import matplotlib
import io
# If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect.
# see: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def show(p):
img = io.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print("%html <div style='width:600px'>" + img.getvalue() + "</div>")
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
show(plt)
The Zeppelin documentation suggests that the following should work:
%python
import matplotlib.pyplot as plt
plt.figure()
(.. ..)
z.show(plt)
plt.close()
This doesn't work for me with Python 3, but looks to be addressed with the soon-to-be-merged PR #1213.
Note that as of Zeppelin 0.7.3, matplotlib integration is much more seamless, so the methods described here are no longer necessary. https://zeppelin.apache.org/docs/latest/interpreter/python.html#matplotlib-integration
As per #eddies suggestion, I tried and this is what worked for me on Zeppelin 0.6.1 python 2.7
%python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.figure()
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
z.show(plt, width='500px')
plt.close()
Change this:
import matplotlib
matplotlib.use('Agg')
with
import matplotlib.pyplot as plt; plt.rcdefaults()
plt.switch_backend('agg')
Complete code example Spark 2.2.0 + python3(anaconda3.5):
%spark.pyspark
import matplotlib.pyplot as plt; plt.rcdefaults()
plt.switch_backend('agg')
import numpy as np
import io
def show(p):
img = io.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print ("%html <div style='width:600px'>" + img.getvalue() + "</div>")
# Example data
people=('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos=np.arange(len(people))
performance=3 + 10 * np.random.rand(len(people))
error=np.random.rand(len(people))
plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')
show(plt)
I would suggest you to use IPython/IPySpark interpreter in zeppelin 0.8.0 which will be released soon. The matplotlib integration in ipython is almost the same as jupyter. There's one tutorial https://www.zepl.com/viewer/notebooks/bm90ZTovL3pqZmZkdS9lN2Q3ODNiODRkNjA0ZjVjODM1OWZlMWExZjM4OTk3Zi9ub3RlLmpzb24

Importing matplotlib does not work

In my terminal window, i open the ipython enviroment, and then type in import matplotlib.pyplot as plt. The error message I get from doing this is:
ImportError Traceback (most recent call last)
<ipython-input-1-eff513f636fd> in <module>()
----> 1 import matplotlib.pyplot as plt
/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
25
26 import matplotlib
---> 27 import matplotlib.colorbar
28 from matplotlib import style
29 from matplotlib import _pylab_helpers, interactive
/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/colorbar.py in <module>()
32 import matplotlib.artist as martist
33 import matplotlib.cbook as cbook
---> 34 import matplotlib.collections as collections
35 import matplotlib.colors as colors
36 import matplotlib.contour as contour
/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/collections.py in <module>()
25 import matplotlib.artist as artist
26 from matplotlib.artist import allow_rasterization
---> 27 import matplotlib.backend_bases as backend_bases
28 import matplotlib.path as mpath
29 from matplotlib import _path
/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/backend_bases.py in <module>()
54
55 import matplotlib.tight_bbox as tight_bbox
---> 56 import matplotlib.textpath as textpath
57 from matplotlib.path import Path
58 from matplotlib.cbook import mplDeprecation
/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/textpath.py in <module>()
20 from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, LOAD_NO_HINTING
21 from matplotlib.ft2font import LOAD_TARGET_LIGHT
---> 22 from matplotlib.mathtext import MathTextParser
23 import matplotlib.dviread as dviread
24 from matplotlib.font_manager import FontProperties
/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/mathtext.py in <module>()
61
62 import matplotlib.colors as mcolors
---> 63 import matplotlib._png as _png
64 ####################
65
ImportError: dlopen(/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2): Library not loaded: #loader_path/../../../libpng15.15.dylib
Referenced from: /Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/_png.so
Reason: image not found
I would truly appreciate a way to resolve this issue. All I want to do is get on with my physics, and all this constant computational setback is quite cumbersome and annoying. I should thus appreciate an expedited response from anyone who may be willing to assist.
Continuum recently updated libpng, which caused this breakage. Sorry for the inconvenience.
The way to fix this error is to run in a terminal
conda update qt
conda update matplotlib
ImportError: dlopen(/Users/arazipinhas/anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2):
Library not loaded: #loader_path/../../../libpng15.15.dylib
really simple: Your matplotlib was linked against libpng15, but that isn't found by your run-time. So you might search for that file, libpng15.15.dylib.
If it's missing, your installation is incomplete and you're probably missing the version of libPNG that was used to build matplotlib.

Categories