Python Forum
Issue plotting coordinates using Basemap
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issue plotting coordinates using Basemap
#1
Having extracted geo coordinates from Twitter JSON, I created a new pandas data frame:

    df3
    Out[140]:
    lat lon pos
    63 -26.298376 28.070223 (-26.29837597, 28.07022309)
    116 1.487180 124.861180 (1.48718, 124.86118)
    199 33.708842 -84.294066 (33.70884247, -84.29406577)
    349 35.368816 -96.955488 (35.36881649, -96.95548791)
    379 14.830463 120.284751 (14.83046326, 120.2847507)
    859 35.151530 -80.727347 (35.15153029, -80.72734744)
Now, my goal is to plot the coordinates on the map using Basemap:

    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
     
    # Set map size
    fig, ax = plt.subplots(figsize=(10,20))

    # Set USA coordinates
    m = Basemap(resolution='c', # c, l, i, h, f or None
            projection='merc',
            lat_0=39, lon_0=-99,  ## center of the map
            llcrnrlon=-125, llcrnrlat= 25, urcrnrlon=-65, urcrnrlat=49)

    # Read county boundaries
    shp_info = m.readshapefile('cb_2015_us_county_500k',
                                   'counties',
                                   drawbounds=True)

    # Set geo coordinates to be plotted 
    lats = df3['lat'] [:]  #all values from column lat
    lons = df3['lon'] [:]  #all values from column lon
    x,y = m(lats, lons)

    # Place points on the map
    m.plot(x, y, 'ro', markersize=5)

    m.bluemarble()
    plt.show()
However, for some reason I get this error:
Error:
    TypeError                                 Traceback (most recent call last)     TypeError: expected a writable bytes-like object     The above exception was the direct cause of the following exception:     SystemError                               Traceback (most recent call last)     <ipython-input-144-d258e6080d9d> in <module>()          18 lats = df3['lat'] [:]          19 lons = df3['lon'] [:]     ---> 20 x,y = m(lats, lons)          21           22 # place it on the map     /Users/mymac/anaconda/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py in __call__(self, x, y, inverse)        1146             except TypeError:        1147                 y = [_dg2rad*yy for yy in y]     -> 1148         xout,yout = self.projtran(x,y,inverse=inverse)        1149         if self.celestial and inverse:        1150             try:     /Users/mymac/anaconda/lib/python3.6/site-packages/mpl_toolkits/basemap/proj.py in __call__(self, *args, **kw)         284             outxy = self._proj4(xy, inverse=inverse)         285         else:     --> 286             outx,outy = self._proj4(x, y, inverse=inverse)         287         if inverse:         288             if self.projection in ['merc','mill','gall']:     /Users/mymac/anaconda/lib/python3.6/site-  packages/mpl_toolkits/basemap/pyproj.py in __call__(self, *args, **kw)         386             _proj.Proj._inv(self, inx, iny, radians=radians, errcheck=errcheck)         387         else:     --> 388             _proj.Proj._fwd(self, inx, iny, radians=radians, errcheck=errcheck)         389         # if inputs were lists, tuples or floats, convert back.         390         outx = _convertback(xisfloat,xislist,xistuple,inx)     _proj.pyx in _proj.Proj._fwd (src/_proj.c:1571)()     SystemError: <class 'RuntimeError'> returned a result with an error set
Can anybody please tell me where I am making a mistake.
Reply
#2
I have no experience with mpl_toolkits, but considering that it is package associated with matplotlib, I wonder what happens if you try
x, y = m(lats.values, lons.values)     # instead of x,y=m(lats, lons)
Reply
#3
It did work! Good catch, sir :)

The result (see attached), however, presents a map with county grid but without coordinates plotted. And the following error. Weird, isn't it? 

Error:
[color=#000000]/Users/mymac/anaconda/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3260: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.  b = ax.ishold() /Users/mymac/anaconda/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3269: MatplotlibDeprecationWarning: axes.hold is deprecated.    See the API Changes document (http://matplotlib.org/api/api_changes.html)    for more details.  ax.hold(b) /Users/mymac/anaconda/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3296: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.  b = ax.ishold() /Users/mymac/anaconda/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3305: MatplotlibDeprecationWarning: axes.hold is deprecated.    See the API Changes document (http://matplotlib.org/api/api_changes.html)    for more details.  ax.hold(b)[/color]

Attached Files

Thumbnail(s)
   
Reply
#4
It is not an error, just a warning about using deprecated function. It seems that some internal function in basemap uses it and according to matplotlib issues it is already patched, so it will disappear after next update. For now you can ignore it.

I downloaded mpl_toolkits and tried it with your code and fictional data. This code:

# Place points on the map
x, y = m(np.array([-104, -100, -90]), np.array([40, 42, 38]))
m.plot(x, y, 'ro', markersize=15)
seems to be working to plot locations, so maybe you need to check your coordinate's values?

[Image: bgBHUtJ.png]
Reply
#5
I switched the coordinates like:
x, y = m(lons.values, lats.values)     # instead of x, y = m(lats.values, lons.values)
...and its all there :) Thanks a lot for help again! I'll double-check how the values were recorded in the data frame.
Reply
#6
Just a suggestion (if you can do this) make the line thickness a bit thinner and white (or at least lighter color) for his view.
In order to work right, that may have to be adjusted when zooming in.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Regression plotting + minor issue mohi_gh 0 1,434 Feb-01-2021, 04:19 PM
Last Post: mohi_gh
  Plotting issue Matplotlib garam0 0 1,474 May-23-2020, 12:11 AM
Last Post: garam0
  Plotting climate data with NetCdf files for a specific region with coordinates fyec 3 5,337 Jun-27-2018, 12:34 PM
Last Post: buran
  basemap problem Roman 2 3,085 Jul-24-2017, 08:48 AM
Last Post: Roman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020