【问题标题】:Plotting data having different dimensions using matplotlib使用 matplotlib 绘制具有不同维度的数据
【发布时间】:2017-01-19 16:44:09
【问题描述】:

我正在尝试使用卫星数据绘制一个简单的图。该数据包含 lat、lon 和 sla(海平面异常)。我用于此示例的数据位于 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()

我面临的问题是 lat 和 lon 包含 164 的形状,而要在底图上绘制的实际变量包含 (164, 83) 的形状。这是我在终端中收到的完整错误消息:-

(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

这是我第一次处理具有不同尺寸/形状的数据。这些具有不同形状的数据是如何绘制的?

【问题讨论】:

  • 我有点困惑,你到底想画什么?如果我理解正确,您有 164 个纬度/经度对和每对 83 个数据点?这 83 点应该如何解释?
  • 实际上,查看此示例可能对docs 有所帮助。可能值得检查示例数据源(这似乎需要安装 osgeo 库)。我还会考虑将问题名称从matplotlib 更改为basemap,因为我发现它与matplotlib 完全不同。
  • 你没有。文档字符串中明确说明:*X* and *Y* must both be 2-D with the same shape as *Z*, or they must both be 1-D such that ``len(X)`` is the number of columns in *Z* and ``len(Y)`` is the number of rows in *Z*.

标签: python matplotlib plot


【解决方案1】:

如果我正确理解Basemap.contourf 的文档,您需要对非结构化数据使用tri 关键字参数:

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

或者可能

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

取决于您的数据是什么。

【讨论】:

  • 我不知道谁对我的问题投了反对票。如果他们不明白,他们应该要求澄清。你给了我正确的答案。感谢您指出错误。
  • 我猜 3 个人对你的问题投了反对票,他们无法看到隐藏在一堆代码背后的真正问题,而这些代码并非直接是 minimal reproducible example。同样乍一看,您似乎在询问如何使用 matplotlibs contourf 绘制具有不同形状的数据,这当然是不可能的,而且人们也可能希望有人在不问问题的情况下发现这一点。放置您使用的 Basemap.contourf 与 matplotlibs contourf 不同的事实可能会阻止这种情况。
猜你喜欢
  • 2019-05-24
  • 2020-10-11
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多