Cartopy not running even with basic introductory example - python

I have installed Cartopy and am now trying to run the basic example code snippet on the tutorial website just to check everything is working:
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
plt.savefig('coastlines.pdf')
plt.savefig('coastlines.png')
plt.show()
I get the following ValueError back:
Traceback (most recent call last):
File "/Users/mattbright/Desktop/SCripts/lattice_geo.py", line 6, in <module>
ax = plt.axes(projection=ccrs.Mollweide())
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 947, in axes
return subplot(111, **kwargs)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 1125, in subplot
ax = fig.add_subplot(*args, **kwargs)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/matplotlib/figure.py", line 1402, in add_subplot
ax = subplot_class_factory(projection_class)(self, *args, **kwargs)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/matplotlib/axes/_subplots.py", line 42, in __init__
self._axes_class.__init__(self, fig, self.figbox, **kwargs)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/cartopy/mpl/geoaxes.py", line 355, in __init__
super(GeoAxes, self).__init__(*args, **kwargs)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 511, in __init__
self.cla()
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/cartopy/mpl/geoaxes.py", line 528, in cla
self._boundary()
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/cartopy/mpl/geoaxes.py", line 1425, in _boundary
trans_path = proj_to_data.transform_path(path)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/matplotlib/transforms.py", line 1527, in transform_path
return self.transform_path_affine(self.transform_path_non_affine(path))
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/cartopy/mpl/geoaxes.py", line 181, in transform_path_non_affine
src_path.vertices, self.source_projection)
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/cartopy/crs.py", line 649, in quick_vertices_transform
if (x.min() >= x_limits[0] and x.max() <= x_limits[1] and
File "/Users/mattbright/opt/miniconda3/lib/python3.7/site-packages/numpy/core/_methods.py", line 43, in _amin
return umr_minimum(a, axis, None, out, keepdims, initial, where)
ValueError: zero-size array to reduction operation minimum which has no identity
I tried the installation with conda and with pip3 plus the list of dependencies given on the website.
There's one previous question about this issue which has gone unanswered since the questioner claimed that an Anaconda reinstall solved the problem. A similar issue with Seaborn has been raised here and solved by reverting to an earlier Matplotlib release (3.3.0)
None of these solutions have worked for me. Has anybody else encountered this and found a way to fix it?

Related

pandas plot, vars() argument must have __dict__ attribute?

It was working perfectly earlier but for some reason now I am getting strange errors.
pandas version: 1.2.3
matplotlib version: 3.7.0
sample dataframe:
df
cap Date
0 1 2022-01-04
1 2 2022-01-06
2 3 2022-01-07
3 4 2022-01-08
df.plot(x='cap', y='Date')
plt.show()
df.dtypes
cap int64
Date datetime64[ns]
dtype: object
I get a traceback:
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/Volumes/coding/venv/lib/python3.8/site-packages/pandas/plotting/_core.py", line 955, in __call__
return plot_backend.plot(data, kind=kind, **kwargs)
File "/Volumes/coding/venv/lib/python3.8/site-packages/pandas/plotting/_matplotlib/__init__.py", line 61, in plot
plot_obj.generate()
File "/Volumes/coding/venv/lib/python3.8/site-packages/pandas/plotting/_matplotlib/core.py", line 279, in generate
self._setup_subplots()
File "/Volumes/coding/venv/lib/python3.8/site-packages/pandas/plotting/_matplotlib/core.py", line 337, in _setup_subplots
fig = self.plt.figure(figsize=self.figsize)
File "/Volumes/coding/venv/lib/python3.8/site-packages/matplotlib/_api/deprecation.py", line 454, in wrapper
return func(*args, **kwargs)
File "/Volumes/coding/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 813, in figure
manager = new_figure_manager(
File "/Volumes/coding/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 382, in new_figure_manager
_warn_if_gui_out_of_main_thread()
File "/Volumes/coding/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 360, in _warn_if_gui_out_of_main_thread
if _get_required_interactive_framework(_get_backend_mod()):
File "/Volumes/coding/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 208, in _get_backend_mod
switch_backend(rcParams._get("backend"))
File "/Volumes/coding/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 331, in switch_backend
manager_pyplot_show = vars(manager_class).get("pyplot_show")
TypeError: vars() argument must have __dict__ attribute
In fact, this problem may cause if you running your code like default script (or in PyCharm interactive console), not in Jupyter.
If it is true, you can fix this error by setting up backend directly in your file with use function:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('TkAgg') # !IMPORTANT
fig, ax = plt.subplots()
res = ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plt some data on the axes.o
# plt.show() # optionally show the result.
In some cases TkAgg may not be available. When firstly check, which backend you use. for this, run this simple code:
import matplotlib as mpl
print(mpl.get_backend())
BUT! this must be runned just by your hands in default terminal, outside of PyCharm. (e.g create simple test.py file, paste code, and run python test.py)
Why? Because PyCharm (at least in scientific projects) runs all files with interactive console, where backend module://backend_interagg is used. And this backend causes same error as you have.
So. add mpl.use('TkAgg') in head of your file, or checkout which backend you can use and past those name in this function.

_tkinter.TclError: couldnt't open ....\matplotlib_128.ppm : no such file or directory

I am new to scripting with Python and this is my first post on stackoverflow (so I hope I phrase this question correctly).
I encountered a problem by using matplotlib. For the sake of this post I simplyfied my code to the lines which cause the problem.
import matplotlib.pyplot as plt
y_vals = [1, 2, 3, 4, 5]
x_vals = [1, 2, 3, 4, 5]
plt.plot(y_vals, x_vals)
plt.show()
When I run the code I recieve the following error message:
File "c:\Users\bachm\Desktop\tmp\GUI_interface.py", line 52, in <module>
ani = FuncAnimation(plt.gcf(), animate, interval = 1, repeat = anim_running)
File "C:\Users\bachm\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\matplotlib\pyplot.py", line 846, in gcf
return figure()
File "C:\Users\bachm\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\matplotlib\pyplot.py", line 787, in figure
manager = new_figure_manager(
File "C:\Users\bachm\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\matplotlib\pyplot.py", line 306, in new_figure_manager
return _backend_mod.new_figure_manager(*args, **kwargs)
File "C:\Users\bachm\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\matplotlib\backend_bases.py", line 3494, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "C:\Users\bachm\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\matplotlib\backends\_backend_tk.py", line 934, in new_figure_manager_given_figure
icon_img = tk.PhotoImage(file=icon_fname, master=window)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 4093, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 4038, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\bachm\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\matplotlib\mpl-data\images\matplotlib_128.ppm": no such file or directory
When I check the directory the file exists and also when running the code (in VS Code) in the interactive mode the plot is generated.
This problem is giving me a huge headache and I cannot figure out why it is not running.
Thanks in advance and in chase something is unclear or phrased wrong please let me know!
Cheers
Try install pip and in cmd write "pip install matplotlib".
Update:
I (think) figured it out and the code is running now. The length of the directory exceeded the number of elements supported (255) by windows.

Plotting densities with seaborn and latex error

I'm trying to plot densities graphs from some data, using seaborn.
It works fine without latex, but when I try to plot with latex, it gives me an error.
Here are the settings:
rcParams['text.usetex'] = True
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
plt.rcParams.update()
sns.set_context("paper")
sns.set(font_scale=1.5, rc={'text.usetex' : True})
sns.set_style('white', {'font.family':'serif', 'font.serif':'Times New Roman', 'background':'white'})
sns.despine()
and the graph is being plotted with:
sns.kdeplot(np.array(data), bw=0.4, cut=0)
plt.tight_layout(True)
plt.savefig('file.png', dpi=300)
Here is the error:
File "plotGraphs.py", line 214, in <module>
plotCarsReached()
File "plotGraphs.py", line 118, in plotCarsReached
plt.tight_layout(True)
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/pyplot.py", line 1337, in tight_layout
gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/figure.py", line 2491, in tight_layout
kwargs = get_tight_layout_figure(
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/tight_layout.py", line 355, in get_tight_layout_figure
kwargs = auto_adjust_subplotpars(fig, renderer,
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/tight_layout.py", line 109, in auto_adjust_subplotpars
tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/tight_layout.py", line 109, in <listcomp>
tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 4317, in get_tightbbox
bb_xaxis = self.xaxis.get_tightbbox(renderer)
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/axis.py", line 1197, in get_tightbbox
bboxes = [
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/axis.py", line 1198, in <genexpr>
*(a.get_window_extent(renderer)
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/text.py", line 905, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/text.py", line 299, in _get_layout
w, h, d = renderer.get_text_width_height_descent(
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py", line 203, in get_text_width_height_descent
w, h, d = texmanager.get_text_width_height_descent(
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/texmanager.py", line 451, in get_text_width_height_descent
with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
File "/Users/iMac/.pyenv/versions/3.8.0/lib/python3.8/site-packages/matplotlib/dviread.py", line 198, in __init__
self.file = open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/Users/iMac/.matplotlib/tex.cache/bff659c457d4aecfc8f90b11c18fa8b1.dvi'
If I remove the initial settings, the plot works.
Other plots using matplotlib instead of seaborn works as well.
Does anybody know how to fix this?
I had the same issue but was able to fix it. The issue is python is not finding latex and kpsewhich files. I resolved the issue by performing the following steps on a Mac and using PyCharm:
Install all recommended packages by Matplotlib latex
brew cask install mactex ghostscript
Manually add latex bin directory path to $PYTHONPATH at the begining in .bash_profile
export PYTHONPATH="/usr/local/texlive/2019/bin/x86_64darwin:/usr/local/bin:$PYTHONPATH"
Worked like a charm - the Matplotlib example output:
Text rendering With LaTeX
Hack to force PyCharm to update it's environment
In the "Run/Edit Configurations":
First uncheck "Add content roots to PYTHONPATH", run it, it will complain about something..
Then check it back on, and run again. This triggers some kind of update about the paths in the target environment
The error was appearing because I had a '%' in one of the axis labels, and I didn't change it to '\%' when I tried to plot it with latex..

savefig() causing ValueError: RGBA values should be within 0-1 range

I'm trying to create a program who will :
Retrieve data from a csv file chosen by the user
Plot the data
Display the figure on the window
Allow the user to change the plot parameters (color, linestyle ...)
Save the plot in a directory chosen by the user in the PS format
Steps 1 to 4 are working just fine, but step 5 makes me feel like I've killed matplotlib ...
I'm using the same syntax I used on a previous version for saving, which worked fine :
def savePlot(self):
self.saveDirectory = QFileDialog.getExistingDirectory(None, 'Chose where you want to save','/home',QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
if self.plotParam==[]:
plt.savefig(self.saveDirectory + "/" + "Untiltled.ps", dpi = 1200)
else :
plt.savefig(self.saveDirectory + "/" + "%s.ps" %self.plotParam[0],format = 'ps', dpi = 1200)
Here is a link to the full code, and here is the data file I'm using.
In this portion, self.plotParam is a list which is initially empty and contains the plot parameters if the user wants to change the default ones.
Here is the error log :
Traceback (most recent call last):
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py", line 141, in to_rgba
rgba = _colors_full_map.cache[c, alpha]
TypeError: unhashable type: 'numpy.ndarray'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/antoine/CERB/courbes/courbesv2.py", line 354, in savePlot
plt.savefig(self.saveDirectory + "/" + "essai.ps", dpi = 1200)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 697, in savefig
res = fig.savefig(*args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/figure.py", line 1573, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt5agg.py", line 222, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2252, in print_figure
**kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 957, in print_ps
return self._print_ps(outfile, 'ps', *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 988, in _print_ps
**kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 1078, in _print_figure
self.figure.draw(renderer)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/figure.py", line 1144, in draw
renderer, self, dsu, self.suppressComposite)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 2426, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/collections.py", line 354, in draw
self._offset_position)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backends/backend_ps.py", line 607, in draw_path_collection
offset_position)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 309, in draw_path_collection
antialiaseds, urls, offset_position):
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 497, in _iter_collection
gc0.set_foreground(fg)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 1027, in set_foreground
self._rgb = colors.to_rgba(fg)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py", line 143, in to_rgba
rgba = _to_rgba_no_colorcycle(c, alpha)
File "/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py", line 204, in _to_rgba_no_colorcycle
raise ValueError("RGBA values should be within 0-1 range")
ValueError: RGBA values should be within 0-1 range
I've tried using different extensions than .ps, and all of them show the same error, except .png, which saves me a disgustingly awfull image, even when it's supposed to be 1200 dpi (I can't post you a link to the saved image as I do not have enough reputation, sorry).
I've also tried doing a "clean path" with os.path.join, but it changed nothing, so I reverted back to the syntax which used to work on the previous version.
I know my code is most likely suboptimal, but I'm learning so it can't be helped ...
Do you have any clues on how to solve this ?
EDIT : Added the minimal, complete and verifiable example :
import matplotlib.pyplot as plt
data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10],[0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2]]
def plotAttempt():
plt.errorbar(data[0],data[1],data[2],0)
path = '/home/PlotAttempt.ps'
plt.savefig(path)
Calling plotAttempt() through the console gets me the same error log
This appears to be a pyzo bug, the code worked just fine when I ran it through the console and after rebooting it also worked on pyzo.

Running a python script with cron, matplotlib error

I am trying to run a python script using cron. The script runs without issue from the command line but has problems with matplotlib when run from cron. The error is below.
Traceback (most recent call last):
File "/home/ubuntu/python/spread.py", line 154, in <module>
plot_spread(lat, lon, vals, mean, maxs, mins, stdp, stdm, ens_members)
File "/home/ubuntu/python/spread.py", line 81, in plot_spread
plt.fill_between(x, maxs, stdp, color='r', alpha=0.2)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 2785, in fill_between
ax = gca()
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 928, in gca
return gcf().gca(**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 578, in gcf
return figure()
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 527, in figure
**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 46, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 53, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 76, in __init__
FigureCanvasQT.__init__(self, figure)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
I got a similar error when I tried to import matplotlib.pyplot in python using cron. You can force matplotlib to not use any Xwindows backend. Do this:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
These links might be also helpful:
Generating a PNG with matplotlib when DISPLAY is undefined
Generating matplotlib graphs without a running X server
Hope this is helpful!

Categories

Resources