1 year ago
#351507
jw99
How to fill a CartoPy map with a Pandas DataFrame
I have a Cartopy Map which looks like this:
As you can see, there is a grid overlaid which is 14x20 grid squares in size.
I also have a data frame, called df, which is also 14x20:
0 1 2 ... 17 18 19
0 NaN NaN NaN ... NaN NaN NaN
1 NaN NaN NaN ... NaN NaN NaN
2 0.022079 0.017996 0.017996 ... 0.011409 0.011409 0.011409
3 0.022079 0.017996 0.017996 ... 0.011409 0.011409 0.011409
4 0.022079 0.017996 0.017996 ... 0.011409 0.011409 0.011409
5 0.022079 0.017996 0.017996 ... 0.011409 0.011409 0.011409
6 0.021927 0.020711 0.020711 ... 0.016651 0.016651 0.016651
7 0.021927 0.020711 0.020711 ... 0.016651 0.016651 0.016651
8 0.021927 0.020711 0.020711 ... 0.016651 0.016651 0.016651
9 0.021927 0.020711 0.020711 ... 0.016651 0.016651 0.016651
10 0.019435 0.021574 0.021574 ... 0.013323 0.013323 0.013323
11 0.019435 0.021574 0.021574 ... 0.013323 0.013323 0.013323
12 0.019435 0.021574 0.021574 ... 0.013323 0.013323 0.013323
13 0.019435 0.021574 0.021574 ... 0.013323 0.013323 0.013323
[14 rows x 20 columns]
I'm trying to fill the dataframe values into the grid cells to plot a Cartopy map. Here's what I've tried:
precip_full1 = xr.open_dataset('era_yr1979.nc')
lon = precip_full1.variables['longitude'][:]
lat = precip_full1.variables['latitude'][:]
lon2d, lat2d = np.meshgrid(lon, lat)
plt.figure(figsize=(6,5))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-15,-10,6.5,10])
ax.coastlines()
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.LAKES)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.BORDERS)
plt.title('Average Rainfall over Sierra Leone')
gl = ax.gridlines(draw_labels=True, xlocs=np.arange(-180,180,0.25), ylocs=np.arange(-90,90,0.25),linewidth=0.4)
gl.top_labels = False
gl.right_labels = False
plot = plt.contourf(lon2d, lat2d, df, cmap = 'YlOrRd', transform=ccrs.PlateCarree())
to which I get:
ValueError: setting an array element with a sequence.
Does anyone know how I could make this work?
EDIT:
Printing Lon and Lat gives:
print(lon)
<xarray.IndexVariable 'longitude' (longitude: 21)>
array([-15. , -14.75, -14.5 , -14.25, -14. , -13.75, -13.5 , -13.25, -13. ,
-12.75, -12.5 , -12.25, -12. , -11.75, -11.5 , -11.25, -11. , -10.75,
-10.5 , -10.25, -10. ], dtype=float32)
Attributes:
units: degrees_east
long_name: longitude
print(lat)
<xarray.IndexVariable 'latitude' (latitude: 15)>
array([10. , 9.75, 9.5 , 9.25, 9. , 8.75, 8.5 , 8.25, 8. , 7.75,
7.5 , 7.25, 7. , 6.75, 6.5 ], dtype=float32)
Attributes:
units: degrees_north
long_name: latitude
python
pandas
dataframe
cartopy
0 Answers
Your Answer