Importing matplotlib on Ubuntu - python

So I downloaded and installed matplotlib. The weird things is that I can run the examples fine when they were placed in home/user/Desktop but when I moved them to home/user/Documents, they stopped working and I get the below message. Is there something special about the Documents folder that they prevent matplotlib from importing?
Traceback (most recent call last):
File "contour_manual.py", line 4, in <module>
import matplotlib.pyplot as plt
File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 23, in <module>
from matplotlib.figure import Figure, figaspect
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 18, in <module>
from axes import Axes, SubplotBase, subplot_class_factory
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes.py", line 8454, in <module>
Subplot = subplot_class_factory()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes.py", line 8446, in subplot_class_factory
new_class = new.classobj("%sSubplot" % (axes_class.__name__),
AttributeError: 'module' object has no attribute 'classobj'

Do you have a file new.py in your Documents folder, by any chance? If you have, try renaming it to something else.
The matplotlib module axes.py imports new, and if you have a file new.py lying around in your Documents folder, that will cause Python to load it instead of the built-in new module.

Related

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

Working on a Mac in Atom.
Running this code
from matplotlib import pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
atom1 = np.random.uniform(-1, 1, 3)
atom2 = np.random.uniform(-1, 1, 3)
atom3 = np.random.uniform(-1, 1, 3)
atom4 = np.random.uniform(-1, 1, 3)
colors = ['r', 'g', 'b', 'k']
atoms = np.vstack([atom1, atom2, atom3, atom4])
ax = plt.subplot(111, projection='3d')
ax.scatter3D(atoms[:, 0], atoms[:, 1], atoms[:, 2], c=colors)
plt.show()
and it always returns
ImportError: cannot import name 'ListedColormap' from partially initialized module 'matplotlib.colors' (most likely due to a circular import) (/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/colors.py)
I recognise that this is a partially initialised module but I don't know how to fix it. I tried uninstalling and reinstalling mpl and np but it still returns the error message.
Any solves?
Full error:
Traceback (most recent call last):
File "/Users/Audey/Desktop/array.py", line 1, in <module>
from matplotlib import pyplot as plt
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/__init__.py", line 109, in <module>
from . import _api, _version, cbook, docstring, rcsetup
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/rcsetup.py", line 27, in <module>
from matplotlib.colors import Colormap, is_color_like
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/colors.py", line 52, in <module>
from PIL.PngImagePlugin import PngInfo
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/PIL/PngImagePlugin.py", line 41, in <module>
from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/PIL/ImagePalette.py", line 19, in <module>
import array
File "/Users/Audey/Desktop/array.py", line 1, in <module>
from matplotlib import pyplot as plt
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/pyplot.py", line 49, in <module>
import matplotlib.colorbar
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/colorbar.py", line 21, in <module>
from matplotlib import _api, collections, cm, colors, contour, ticker
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/collections.py", line 20, in <module>
from . import (_api, _path, artist, cbook, cm, colors as mcolors, docstring,
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/artist.py", line 15, in <module>
from .cm import ScalarMappable
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/cm.py", line 26, in <module>
from matplotlib._cm_listed import cmaps as cmaps_listed
File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/_cm_listed.py", line 1, in <module>
from .colors import ListedColormap
ImportError: cannot import name 'ListedColormap' from partially initialized module 'matplotlib.colors' (most likely due to a circular import) (/Users/Audey/Library/Python/3.10/lib/python/site-packages/matplotlib/colors.py)
The problem, evident from "/Users/Audey/Desktop/array.py" in your traceback is that you've named your script array.py.
array is also a standard library module, so Python's import machinery gets "confused" and where PIL would like to import the standard library module, it gets your module.
Rename your script to something that's not a standard library module, say, audeys_array.py. Also take care to see that there isn't an array.pyc left behind.
You have named your file array.py which clashes with the array module of the standard library. You should rename your file and make sure there are not .pyc files left over.
It's difficult to say whats wrong.
I tried to run your code on my pc and it's working (Ubuntu + PyCharm), but...
Some imports are unused in example code:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
Try to run your code in virtual environment. From returned error text I see that you maybe run code with global python and maybe some of global denedencies affects it.

AttributeError: partially initialized module x has no attribute y (most likely due to a circular import)

I want to use pandas to process a csv file. The main job is to duplicate a column, so I name the script file as copy.py.
import pandas as pd
df = pd.read_csv('latex.csv')
However, when I execute the file, it gets the error
$ python copy.py
Traceback (most recent call last):
File "~/sourcecode/rime-math/copy.py", line 1, in <module>
import pandas as pd
import pandas as pd
File "~/.local/lib/python3.10/site-packages/pandas/__init__.py", line 50, in <module>
from pandas.core.api import (
File "~/.local/lib/python3.10/site-packages/pandas/core/api.py", line 48, in <module>
from pandas.core.groupby import (
File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/__init__.py", line 1, in <module>
from pandas.core.groupby.generic import (
File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/generic.py", line 73, in <module>
from pandas.core.frame import DataFrame
File "~/.local/lib/python3.10/site-packages/pandas/core/frame.py", line 129, in <module>
from pandas.core import (
File "~/.local/lib/python3.10/site-packages/pandas/core/generic.py", line 122, in <module>
from pandas.core.describe import describe_ndframe
File "~/.local/lib/python3.10/site-packages/pandas/core/describe.py", line 37, in <module>
from pandas.core.reshape.concat import concat
File "~/.local/lib/python3.10/site-packages/pandas/core/reshape/concat.py", line 45, in <module>
from pandas.core.internals import concatenate_managers
File "~/.local/lib/python3.10/site-packages/pandas/core/internals/__init__.py", line 17, in <module>
from pandas.core.internals.concat import concatenate_managers
File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
import copy
File "~/sourcecode/rime-math/copy.py", line 4, in <module>
df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)
The problem is that the name of your script file is collision with the file one of your module wants to import.
Put attention on the last 5 lines of the traceback since it is near line where error occurs:
File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
import copy
File "~/sourcecode/rime-math/copy.py", line 4, in <module>
df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)
Look at the first 2 lines, it means pandas module need to import copy module at somewhere.
According to The Module Search Path, Python interpreter will search copy module in built-in modules, current directory, PYTHONPATH etc. in order.
Apparently there is no built-in modules named copy in Python, so the interpreter will then look at the files under current directory and find there is copy.py.
The content of copy.py is just one line: df = pd.read_csv(). It means we need to use pandas module. However, we are just on the way importing pandas. Pandas here is only partially initialized, that's why you see that information in backtrace.
To solve this is easy, rename the script file copy.py to some others is ok.

Getting the following error: AttributeError: module 'pandas' has no attribute 'read_csv'

I have looked at several other similar questions but their fixes are not working for me. I am running my script in a conda venv but I already installed pandas within said environment. I will show my code and the error I get when running from the terminal. Obviously, the directory of the virtual environment is not the same as the directory of my css file, which is why I give the file path to the file. I must add that within VS Code, I am able to get the data set and add items to the list I created (although the while loop is not currently working). Can anyone help?
import pandas as pd
import random
data_set = pd.read_csv("/Users/rickvillanueva/Documents/Myron/dated_random.csv")
random_data = data_set.MYRON_ACCT
random_names = []
random_gatherer = True
#Gathering random account numbers
while random_gatherer:
one = random.choice(random_data)
random_names.append(one)
if len(random_names) < 50:
random_gatherer = True
continue
else:
break
len(random_names)
print(random_names)
Error I get in terminal:
Traceback (most recent call last):
File "random.py", line 1, in <module>
import pandas as pd
File "/Users/rickvillanueva/opt/anaconda3/lib/python3.7/site-packages/pandas/__init__.py", line 11, in <module>
__import__(dependency)
File "/Users/rickvillanueva/opt/anaconda3/lib/python3.7/site-packages/numpy/__init__.py", line 152, in <module>
from . import random
File "/Users/rickvillanueva/opt/anaconda3/lib/python3.7/site-packages/numpy/random/__init__.py", line 181, in <module>
from . import _pickle
File "/Users/rickvillanueva/opt/anaconda3/lib/python3.7/site-packages/numpy/random/_pickle.py", line 1, in <module>
from .mtrand import RandomState
File "_bit_generator.pxd", line 14, in init numpy.random.mtrand
File "_bit_generator.pyx", line 40, in init numpy.random._bit_generator
File "/Users/rickvillanueva/opt/anaconda3/lib/python3.7/secrets.py", line 20, in <module>
from random import SystemRandom
File "/Users/rickvillanueva/Documents/Myron/random.py", line 5, in <module>
data_set = pd.read_csv("/Users/rickvillanueva/Documents/Myron/dated_random.csv")
AttributeError: module 'pandas' has no attribute 'read_csv'

Matplotlib wont import, showing up as a type error

I'm on an osx machine. Matplotlib was working fine a few days back, but today when i wanted to use it it just won't import. There are a bunch of lines and at the bottom it gives me a type error goes on about a copy function needing another variable. I've tried reinstalling it and still wont budge. any thoughts? I'm still fairly new to this so i have no idea whats going on.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/__init__.py", line 138, in <module>
from . import cbook, rcsetup
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/rcsetup.py", line 24, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/fontconfig_pattern.py", line 18, in <module>
from pyparsing import (Literal, ZeroOrMore, Optional, Regex, StringEnd,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 5658, in <module>
_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group(OneOrMore(_charRange | _singleChar)).setResultsName("body") + "]"
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 1480, in setResultsName
return self._setResultsName(name, listAllMatches)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 1483, in _setResultsName
newself = self.copy()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 1437, in copy
cpy = copy.copy(self)
TypeError: copy() missing 2 required positional arguments: 'E' and 'X'
Not sure if it's related, but when I migrated to OSX I had problems with matplotlib which were solved by changing the backend:
import matplotlib
matplotlib.use("MacOSX")
Thanks for the response, it turns out matplotlib didn't like the directory I was in, which is odd. Just changing where i was trying to run it from worked.

bundle_files = 1 fails with py2exe using matplotlib

I am trying to create a standalone application using py2exe that depends on matplotlib and numpy. The code of the application is this:
import numpy as np
import pylab as plt
plt.figure()
a = np.random.random((16,16))
plt.imshow(a,interpolation='nearest')
plt.show()
The setup code for py2exe (modified from http://www.py2exe.org/index.cgi/MatPlotLib) is this:
from distutils.core import setup
import py2exe
import sys
sys.argv.append('py2exe')
opts = {
'py2exe': {"bundle_files" : 3,
"includes" : [ "matplotlib.backends",
"matplotlib.backends.backend_qt4agg",
"pylab", "numpy",
"matplotlib.backends.backend_tkagg"],
'excludes': ['_gtkagg', '_tkagg', '_agg2',
'_cairo', '_cocoaagg',
'_fltkagg', '_gtk', '_gtkcairo', ],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll']
}
}
setup(console=[{"script" : "matplotlib_test.py"}],
zipfile=None,options=opts)
Now, when bundle_files is set = 3 or is absent, all works fine, but the resulting exe cannot be distributed to a machine that is not configured with the same version of Python, etc. If I set bundle_files = 1, it creates a suitably large exe file that must have everything bundled, but it fails to run locally or distributed. In this case, I'm creating everything on a Windows 7 machine with Python 2.6.6 and trying to run locally and on an XP machine with Python 2.6.4 installed.
The errors I get when running on the XP machine seem strange since, without bundling, I get no errors on Win 7. With bundling, Win 7 does not report the traceback information, so I cannot be sure the errors are the same. In any case, here's the error message on XP:
Traceback (most recent call last):
File "matplotlib_test.py", line 2, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "pylab.pyc", line 1, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "matplotlib\__init__.pyc", line 709, in <module>
File "matplotlib\__init__.pyc", line 627, in rc_params
File "matplotlib\__init__.pyc", line 565, in matplotlib_fname
File "matplotlib\__init__.pyc", line 240, in wrapper
File "matplotlib\__init__.pyc", line 439, in _get_configdir
RuntimeError: Failed to create C:\Documents and Settings\mnfienen/.matplotlib; c
onsider setting MPLCONFIGDIR to a writable directory for matplotlib configuratio
n data
Many thanks in advance if anyone can point me in a direction that will fix this!
EDIT 1:
I followed William's advice and fixed the problem with MPLCONFIGDIR, but now get a new error:
:Traceback (most recent call last):
File "matplotlib\__init__.pyc", line 479, in _get_data_path
RuntimeError: Could not find the matplotlib data files
EDIT 2:
I fixed the data files problem by using:
data_files=matplotlib.get_py2exe_datafiles()
This leads to a new error:
Traceback (most recent call last):
File "matplotlib_test.py", line 5, in <module>
import matplotlib.pyplot as plt
File "matplotlib\pyplot.pyc", line 78, in <module>
File "matplotlib\backends\__init__.pyc", line 25, in pylab_setup
ImportError: No module named backend_wxagg
I had the same problem. I think the problem was caused by pylab in matplotlib, py2exe seemed to have trouble finding and getting all the backends associated with pylab.
I got around the problem by changing all my embedded plots to use matplotlib.figure instead of pylab. Here's a simple example on how to make a plot with matplotlib.figure:
import matplotlib.figure as fg
import numpy as np
fig = fg.Figure()
ax = fig.add_subplot(111)
lines = ax.plot(range(10), np.random.randn(10), range(10), np.random.randn(10))
You cannot use fig.show() directly with this, but it can be embedded in GUIs. I used Tkinker:
canvas = FigureCanvasTkAgg(fig, canvas_master)
canvas.show()
Well Misha Fienen, I guess it seems to be failing to write to your user folder, which you probably already knew. Just a stab in the dark but have you tried testing what happens if you follow the advice and change MPLCONFIGDIR to something a bit more basic (eg. "C:\matlibplotcfg\")?
There are two ways of solving the problem.
1.- In your matplotlib.rc file use:
backend : TkAgg
2.- alternatively, in your setup.py "includes" key add:
"matplotlib.backends.backend_wxagg"
both ways produce the test figure in Python 2.6, windows XP

Categories

Resources