gpt4 book ai didi

python - (Python) 无法查看 Matplotlib 图

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:44 27 4
gpt4 key购买 nike

我正在使用以下代码尝试使用 matplotlib 生成等高线图。

脚本代码:

#!/usr/bin/python

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy as np
from matplotlib.mlab import griddata

a = np.loadtxt('/home/weather/site_data')

def show_map(self, a):

# 'a' is of the format [(lats, lons, data), (lats, lons, data)... (lats, lons, data)]
lats = [ x[0] for x in a ]
lons = [ x[1] for x in a ]
data = [ x[2] for x in a ]

lat_min = min(lats)
lat_max = max(lats)
lon_min = min(lons)
lon_max = max(lons)
data_min = min(data)
data_max = max(data)

spatial_resolution = 0.5
fig = plt.figure()

x = np.array(lons)
y = np.array(lats)
z = np.array(data)

xinum = (lon_max - lon_min) / spatial_resolution
yinum = (lat_max - lat_min) / spatial_resolution
xi = np.linspace(lon_min, lon_max + spatial_resolution, xinum) # same as [lon_min:spatial_resolution:lon_max] in matlab
yi = np.linspace(lat_min, lat_max + spatial_resolution, yinum) # same as [lat_min:spatial_resolution:lat_max] in matlab
xi, yi = np.meshgrid(xi, yi)

zi = griddata(x, y, z, xi, yi)

m = Basemap(
projection = 'merc',
llcrnrlat=lat_min, urcrnrlat=lat_max,
llcrnrlon=lon_min, urcrnrlon=lon_max,
rsphere=6371200., resolution='l', area_thresh=10000
)

m.drawcoastlines()
m.drawstates()
m.drawcountries()

lat, lon = m.makegrid(zi.shape[1], zi.shape[0])
x,y = m(lat, lon)
m.contourf(x, y, zi)

plt.show()

数据:

[(45.43, -75.65, 75.9), (44.30, -73.63, 85.2), (45.76, -65.76, 68.2)]

我试图弄清楚我是否输入了错误的数据,或者是否存在其他潜在问题。

我不断收到以下错误代码:

ValueError: could not convert string to float: [(45.43,

我尝试自己修复它,并认为我通过删除所有括号和逗号来解决它,但是,然后脚本甚至没有绘制图像。

最佳答案

我将您的输入数据文件更改为如下所示,我相信这是 np.loadtxt() 正在寻找的格式

45.43 -75.65 75.9
44.30 -73.63 85.2
45.76 -65.76 68.2

至于为什么你看不到图像,我从函数参数中删除了 self ,并调用了

show_map(a)

plt.show() 之前的一行。您实际上从未在代码块中调用函数 show_map(),这就是它没有执行的原因。我获得了一张如下所示的图片:

enter image description here

这可能是也可能不是您正在寻找的内容(我以前从未使用过 basemap )。希望这会有所帮助。

关于python - (Python) 无法查看 Matplotlib 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31657675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com