简体   繁体   中英

Python : Cartopy and pcolormesh, do a loop

I an actually in internship, and I want to plot some temperature of the ocean surface data of a map for each months for on years (I want for 50 years but I will see later) and I want it to be focus on a precise area. I have succeed to do this except that when I plot my data, in each maps (12 maps for each months). I have the same data on every months, it seems that the temperature for January are in each maps. It is probably a problem with this line:

ax.pcolormesh(lon, lat, tos, data=dset, cmap=cmap)

But I don't know how to fix it. Maybe I have to do a other loop inside this code line, but is it possible ? Thanks for your answers !

Code :

from netCDF4 import Dataset
import matplotlib.pylab as plt
import cartopy.crs as ccrs
import numpy as np
import netCDF4 as nc

month_name=["Jan","Feb","Mar","Apr","May","June","Jul","Aug","Sep","Oct","Nov","Dec"]

data = "/Users/name/Desktop/Internship/tos_1979.nc" 
dset = Dataset(data)
fig = plt.figure(figsize=(24,24))
cmap = plt.cm.jet
for imonth in np.arange(1,13):  
ax = fig.add_subplot(4,3,imonth, projection=ccrs.PlateCarree())   
  tos = dset.variables['tos'][0, :, :]
  lon = dset.variables['longitude'][:]
  lat = dset.variables['latitude'][:]
  time = dset.variables['time'][:]

  ax.set_extent([-70,20,30,90])
  ax.coastlines();
  plt.title('Ocean Surface Temperature :'+ month_name[imonth-1],fontsize=12
  ax.stock_img()
  ax.gridlines()
  ax.pcolormesh(lon, lat, tos, data=dset, cmap=cmap)
plt.savefig('fig_tos_1979.png')
plt.show()

Just to know, I code with Python, on a MacBook (with Spyder).

Also I have problem with the scalebar tool, it's install on my Mac (thanks to the terminal) but when I import this tools it's says :

  ImportError: cannot import name 'scale_bar' from 'scalebar' (/Users/name/opt/anaconda3/lib/python3.9/site-packages/scalebar/__init__.py)

Thanks !

It's probably because you have hard coded the indexing of the data with 0 .

So perhaps change this:
tos = dset.variables['tos'][0, :, :]

To:
tos = dset.variables['tos'][imonth-1, :, :]

But I'm guessing since I don't know the layout of your data.

You could also try loading the data with Xarray, and then leverage some of the convenience functions for plots like this. See:
https://docs.xarray.dev/en/stable/user-guide/plotting.html#faceting

That still uses Matplotlib+Cartopy in the background, but might provide an easier interface when you're getting started.

(I'm not familiar with the scalebar module at all...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM