Add world street map to basemap - python

I am having problems with basemap - arcgisimage function. Sample code below
...
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from PIL import Image
m = Basemap(
llcrnrlat=40.361369, llcrnrlon=-80.0955278,
urcrnrlat=40.501368, urcrnrlon=-79.865723,
epsg = 2272
)
#m.arcgisimage(service='ESRI_StreetMap_World_2D'
, xpixels=7000, verbose=True)
m.arcgisimage(service='World_Physical_Map', xpixels=7000, ypixels=None, dpi=96,verbose=True)
#m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels=7000, verbose=True)
plt.show()
...
when I run this the arcgisimage() function crashes in PIL with error message
Traceback (most recent call last):
File "C:\Machine Learning\Geospatial\pittsburgh_map.py", line 11, in <module>
m.arcgisimage(service='World_Physical_Map', xpixels=7000, ypixels=None, dpi=96,verbose=True)
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\mpl_toolkits\basemap\__init__.py", line 4263, in arcgisimage
return self.imshow(imread(urlopen(basemap_url)),ax=ax,
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\image.py", line 1490, in imread
with img_open(fname) as image:
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\ImageFile.py", line 121, in __init__
self._open()
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\PngImagePlugin.py", line 692, in _open
cid, pos, length = self.png.read()
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\PngImagePlugin.py", line 162, in read
pos = self.fp.tell()
io.UnsupportedOperation: seek

I had the same problem, most probably you have installed it using conda. I deinstalled the basemap module and reinstalled it with pip. then everything worked normally

If you followed the basemap installation instructions, then any issues you have with running basemap will probably remain unfixed as it is is deprecated in favor of cartopy https://github.com/matplotlib/basemap.

Related

Python -- Pandas can't find file but numpy can

I am at a complete loss here. I am trying to open a txt file in pandas, I have tried multiple different approaches, but I receive the same error message every time. 'no such file'...
What is strange is that this...
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
full_file = np.loadtxt('2_Feature_Test.txt', delimiter=',')
...works completely fine, however this...
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
full_file = pd.read_csv('2_Feature_Test.txt', sep=',')
...does not.
Doesn't matter full path, doesn't matter backslashes or forward slashes or prefixing with r for raw string. Is the problem something to do with pandas and numpy being in different locations? I have no clue. Please, if you have any ideas I am all ears and would love nothing more than to get to the bottom of this. Thanks everyone.
If it helps, this is the full error message I receive...
Traceback (most recent call last):
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\workbench.py", line 1449, in event_generate
handler(event)
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 138, in handle_toplevel_response
self._explain_exception(msg["user_exception"])
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 178, in _explain_exception
+ _error_helper_classes["*"]
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 176, in <listcomp>
for helper_class in (
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\plugins\stdlib_error_helpers.py", line 555, in __init__
super().__init__(error_info)
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 478, in __init__
self.last_frame_module_source = read_source(self.last_frame.filename)
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\common.py", line 252, in read_source
with tokenize.open(filename) as fp:
File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\tokenize.py", line 447, in open
buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'pandas\\_libs\\index.pyx'
UPDATE: due to a more patient man than I actually reading the error message, I realize the issue is most likely with the pandas installation. Install of pandas via conda install pandas failed saying 'the specified procedure could not be found'. Might this have something to do with the issue? Anybody seen this before?
As the comments have said, clearly the missing file is one of pandas', not the file you are trying to read.
Try forcing the reinstall of pandas
pip install -I pandas
or, if using Anaconda
conda install pandas --force-reinstall

Can't use pyplot due to _tkinter.TclError: unknown color name

I've got a simple code:
from matplotlib import pyplot as plt
plt.plot([1,2,5])
plt.show()
It works fine in jupyter notebook, however when I try to run it using command line:
$ python3 main.py
It throws an error:
_tkinter.TclError: unknown color name "[97]#282a36"
The whole trackeback:
Traceback (most recent call last):
File "main.py", line 2, in <module>
plt.plot([1,2,5])
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 2811, in plot
return gca().plot(
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 935, in gca
return gcf().gca(**kwargs)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 578, in gcf
return figure()
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 525, in figure
**kwargs)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 3218, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/backends/_backend_tk.py", line 1008, in new_figure_manager_given_figure
window = Tk.Tk(className="matplotlib")
File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: unknown color name "[97]#282a36"
I already tried changing matplotlib's backend:
import matplotlib
matplotlib.use('pdf') # Or using other arguments matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,5])
plt.show()
It gives me the same error message.
I also tried installing matplotlib using pip and my distribution package manager, both giving me the same error.
tkinter has been installed from my distribution repositories.
Any suggest would be helpful, I couldn't find any solution on similar questions.
After reading this issue on matplotlib's Github page, I emptied out my .Xresources and it fixed the issue.
So I looked a little bit more into the .Xresources file and I found out a line:
*background: [97]#282a36
Which was the cause of matplotlib complaining about a color nameed: [97]#282a36:
_tkinter.TclError: unknown color name "[97]#282a36"
Removing [97] from the line fixed the issue. remember that you have to run:
xrdb -merge .Xresources
To make the changes take place.

RuntimeError: Invalid DISPLAY variable

I am running my python script in another machine by using ssh command in linux. I have also run this command :
source ~/.bashrc
after logging in the other machine, in order to define the proper paths in the new machine. I was getting the error message for running the following python code lines even I have tried to follow the instruction in this question by defining the backend.
>>> import matplotlib
>>> import pylab as plt
>>> matplotlib.use('Agg')
>>> import numpy as np
>>> x=np.arange(0,2,0.001)
>>> y=np.sin(x)**2+4*np.cos(x)
>>> fig = plt.figure()
>>> plt.plot(x,y,'r.')
The error message
This probably means that Tcl wasn't installed properly.
Traceback (most recent call last):
File "Systematic_Optimised.py", line 513, in <module>
fig = plt.figure()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 47, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 54, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 72, in __init__
FigureCanvasQT.__init__(self, figure)
File "/vol/aibn84/data2/zahra/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
any suggestion how to fix the problem
You must declare matplotlib.use('agg') before import pylab as plt.
Reference
Add
plt.switch_backend('agg')
after
import matplotlib.pyplot as plt

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!

"dvipng: not found" when creating matplotlib figure

I try to plot a frequency histogram with matplotlib but it doesn t work and i don t know where is the problem...
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
data = np.array([58.35, 71.83, 49.25, 38.89, 12.6, 58.34, 34.5, 11.6, 64.66, \
89.14, 101.84, 26.91, 38.74, 65.03, 35.23, 70.73, 54.52, 73.36, 74.35, \
60.54, 73.52, 24.58, 50.31, 55.63, 14.6, 53.64, 81.6])
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
n, bins, patches=ax.hist(data, 10, facecolor='green', alpha=0.75)
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, pos: ('%.2f')%(y*1e-3)))
ax.set_ylabel('Frequency (000s)')
plt.show()
A part of the error message :
sh: 1: dvipng: not found
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 276, in resize
self.show()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1034, in draw
func(*args)
...
In Ubuntu 14.04 I used this command to solve the problem:
sudo apt-get install dvipng
It looks like you are having a problem with the renderer or backend. You might want to try a different backend, by adding this at the beginning of your code:
import matplotlib as mpl
mpl.use('macOsX')
For other renderers, see here:
http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
I found that if you have some Latex distr. installed you may also go with:
sudo tlmgr install dvipng
This is especially helpful for Mac, alternatively you can use ports:
sudo port install dvipng
For MacOS add this to your code!
import matplotlib as mpl
mpl.use('macOsX')

Categories

Resources