简体   繁体   中英

Plotting data having different dimensions using matplotlib

I am trying to plot a simple plot using satellite data. This data contain lat, lon and sla (sea level anomaly). The data I used for this example is located here This the simple script I am trying to started experiment with is here:-

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import platform
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

width = 10
height = 8

nc_f = ('ctoh.sla.ref.RA2.medsea.0543.nc')
nc_fid = Dataset(nc_f, 'r')
lons = nc_fid.variables['lon'][:]
lats = nc_fid.variables['lat'][:]
sla = nc_fid.variables['sla'][:]

lon_0 = lons.mean()
lot_0 = lats.mean()
lon_max = nc_fid.variables['lon'].lon_max
lon_min = nc_fid.variables['lon'].lon_min
lat_min = nc_fid.variables['lat'].lat_min
lat_max = nc_fid.variables['lat'].lat_max

m = Basemap(projection='merc', lat_0=lot_0, lon_0=lon_0,
            resolution = 'l', llcrnrlon=lon_min, llcrnrlat=lat_min,
            urcrnrlon=lon_max, urcrnrlat=lat_max)
m.drawcoastlines()
m.drawcountries(linewidth=1.0)
# lons,lats= np.meshgrid(lons, lats)
x, y = m(lons, lats)
# plt.figure(figsize=(width, height), frameon=False)
# plt.contourf(x, y, sla)
print(y.shape)
print(x.shape)
print(sla.shape)
cs = m.contourf(x, y, sla)
plt.contourf(np.reshape(x, sla.shape), np.reshape(y, sla.shape), sla)
plt.show()

What is the problem I am facing is that the lat and lon contain a shape of 164 and the actual variable to be plotted on basemap contain a shape of (164, 83). Here is the complete error message I have got in terminal:-

(164,)
(164,)
(164, 83)
Traceback (most recent call last):
  File "satellite.py", line 39, in <module>
    cs = m.contourf(x, y, sla)
  File "/home/sundar/.anaconda2/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.py", line 521, in with_transform
    return plotfunc(self,x,y,data,*args,**kwargs)
  File "/home/sundar/.anaconda2/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.py", line 3644, in contourf
    xx = x[x.shape[0]/2,:]
IndexError: too many indices for array

This is the first time I am dealing with data having diffent dimensions/ shapes. How do these data having different shapes are plotted?

If I understand the documentation of Basemap.contourf correctly, you need to use the tri keyword argument for unstructured data:

cs = m.contourf(lon, lat, sla, tri=True)

or possibly

cs = m.contourf(x,y, sla, tri=True)

depending on what your data is.

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