【问题标题】:Lines not plotting on graph using Python/Basemap没有使用 Python/底图在图形上绘制的线
【发布时间】:2013-10-30 09:11:57
【问题描述】:

对不起,如果这个问题很简单,我是使用 Python 和底图的新手。无论如何,我正在尝试在地图(图表)上绘制 20 场飓风的路径。地图本身和图例完美显示,但飓风的路径却没有。此外,我没有收到任何回溯消息,但我想我知道我的问题可能出在哪里。谁能告诉我哪里出错了。

这是 csv 文件的示例:

Year, Name, Type, Latitude, Longitude
1957,AUDREY,HU, 21.6, 93.3
1957,AUDREY,HU,22.0,  93.4
1957,AUDREY,HU,22.6,  93.5
1969,AUDREY,HU,28.2,99.6
1957,AUDREY,HU,26.5,93.8
1957,AUDREY,HU,27.9,93.8
1957,AUDREY,HU,29.3,95
1957,AUDREY,HU,27.9,93.8
1957,AUDREY,HU,29.3,93.8
1957,AUDREY,HU,30.7,93.5
1969,CAMILLE,HU, 21.6,99.3
1969,CAMILLE,HU,22.0,98.4
1969,CAMILLE,HU,22.6,90.5
1969,CAMILLE,HU,23.2,93.6

这是我目前的代码:

import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import csv, os, scipy
import pandas
from PIL import *


data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=1)
'''print data'''
fig = plt.figure(figsize=(12,12))

ax = fig.add_axes([0.1,0.1,0.8,0.8])

m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57.,
            projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,
            resolution ='l',area_thresh=1000.)

m.bluemarble()
m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=0.5)
m.drawstates(linewidth=0.5)

# Creates parallels and meridians
m.drawparallels(np.arange(10.,35.,5.),labels=[1,0,0,1])
m.drawmeridians(np.arange(-120.,-80.,5.),labels=[1,0,0,1])
m.drawmapboundary(fill_color='aqua')
color_dict = {'AUDREY': 'red', 'ETHEL': 'white', 'BETSY': 'yellow','CAMILLE': 'blue', 'CARMEN': 'green','BABE': 'purple', }


colnames = ['Year','Name','Type','Latitude','Longitude']
data = pandas.read_csv('louisianastormb.csv', names=colnames)
names = list(data.Name)
lat = list(data.Latitude)
long = list(data.Longitude)
colorName = list(data.Name)
#print lat
#print long
lat.pop(0)
long.pop(0)
colorName.pop(0)
latitude= map(float, lat)
longitude = map(float, long)
x, y = m(latitude,longitude)
#Plots points on map
for colorName in color_dict.keys():
    plt.plot(x,y,linestyle ='-',label=colorName,color=color_dict[colorName], linewidth=5 )
    lg = plt.legend()
    lg.get_frame().set_facecolor('grey')
plt.show()

【问题讨论】:

  • 您是否也可以上传 csv 数据文件,或者只是一个精简版本的最小工作示例?
  • @nye17 当然,我刚刚添加了一个 csv 文件的样本。我无法上传整个文件。

标签: python numpy matplotlib pandas matplotlib-basemap


【解决方案1】:

您的代码有两个(好吧,我撒谎了,应该存在)问题

i,您的输入经度应为负值,以在您为底图定义的边界内,因此在转换为 x 和 y 之前添加此值

longitude = [-i for i in longitude]

ii,你的坐标转换线错了,你应该在参数列表中交换lon和lat

x, y = m(longitude, latitude)

而不是

x, y = m(latitude,longitude)

编辑:

好的,OP在cmets中发布的第二个问题,请查看下面的完整代码,并注意我所做的与您相比的更改

# Last-modified: 21 Oct 2013 05:35:16 PM

import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import csv, os, scipy
import pandas
from PIL import *


data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=1)
'''print data'''
fig = plt.figure(figsize=(12,12))

ax = fig.add_axes([0.1,0.1,0.8,0.8])

m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57.,
            projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,
            resolution ='l',area_thresh=1000.)

m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=0.5)
m.drawstates(linewidth=0.5)
# m.bluemarble(ax=ax)

# Creates parallels and meridians
m.drawparallels(np.arange(10.,35.,5.),labels=[1,0,0,1])
m.drawmeridians(np.arange(-120.,-80.,5.),labels=[1,0,0,1])
m.drawmapboundary(fill_color='aqua')
color_dict = {'AUDREY': 'red', 'ETHEL': 'white', 'BETSY': 'yellow','CAMILLE': 'blue', 'CARMEN': 'green','BABE': 'purple', }

colnames = ['Year','Name','Type','Latitude','Longitude']
data = pandas.read_csv('louisianastormb.csv', names=colnames)
names = list(data.Name)
lat = list(data.Latitude)
long = list(data.Longitude)
colorNames = list(data.Name)
#print lat
#print long
lat.pop(0)
long.pop(0)
colorNames.pop(0)
latitude= map(float, lat)
longitude = map(float, long)
# added by nye17
longitude = [-i for i in longitude]
# x, y = m(latitude,longitude)
x, y = m(longitude,latitude)
# convert to numpy arrays
x = np.atleast_1d(x)
y = np.atleast_1d(y)
colorNames = np.atleast_1d(colorNames)
#Plots points on map
for colorName in color_dict.keys():
    plt.plot(x[colorName == colorNames],y[colorName == colorNames],linestyle ='-',label=colorName,color=color_dict[colorName], linewidth=5 )
    lg = plt.legend()
    lg.get_frame().set_facecolor('grey')
plt.show()

【讨论】:

  • 非常感谢!!!然而,现在所有的线条都以相同的颜色绘制。我该如何解决这个问题,以便飓风的路径与我的颜色字典中的颜色相匹配。例如飓风奥黛丽的路径是红色的,埃塞尔的路径是蓝色的,等等。
  • @mikez1 您应该在每个线程中问一个问题。如果这个答案解决了您在原始帖子中提出的问题,那么您应该接受它(灰色大复选框)如果您有更多或新问题,您应该创建一个新问题线程。
  • @tcaswell 好的,抱歉。
  • @mikez1 听 tcaswell,但就这一次,请检查我编辑的答案。
  • @mikez1 你好像是新来的,所以不要太担心。每个线程一个问题的逻辑是使该站点对未来的读者尽可能有用。这也有助于不要让答案变得疯狂,当目标帖子不断移动时非常令人沮丧。
【解决方案2】:

我认为你在底图中的困难并不在于绘图。无需绘制整个 x/y 数据集,您需要找到对应于飓风 Z 的 x/y 点。然后仅绘制具有特定颜色 c 的那些点。然后找到下一个飓风等对应的点...

下面,虽然不使用 Basemap 数据结构,但应该提供一个起点,用于根据某些选择器向量绘制点的子集。

#given a list of x,y coordinates with a  label we'll plot each line individually

#first construct some points to plot
x1 = [1,1.1,1.2,1.3, 2.0,2.2,2.3, 4,3.9,3.8,3.7]
y1 = [5,5.1,5.2,5.3, 6.0,6.2,6.3, 2,2.1,2.2,2.3]
pointNames = []
#generate some labels
pointNames.extend(['a']*4)
pointNames.extend(['b']*3)
pointNames.extend(['c']*4)

#make things easy by casting to numpy arrays to allow for easier indexing
x1 = numpy.array(x1)
y1 = numpy.array(y1)
pointNames = numpy.array(pointNames)

for elem in ['a','b','c']:
  selector = pointNames==elem
  subsetX = x1[selector]
  subsetY = y1[selector]
  #now plot subsetX vs subsetY in color Z
  plot(subsetX,subsetY,'*-')

show()

【讨论】:

  • 好的,感谢您的回复。我想我明白你在说什么,但我有一个包含 20 个飓风、类型和坐标等的文件。有没有一种简单的方法可以根据飓风的名称对所有坐标进行分组并绘制它们?
  • 当然,在这种情况下,您可以使用 set 函数来获取唯一的字符串名称(飓风)。 s1 = set(['a','b','c','c']) 给出 s1:('a','b','c') 作为元组。你可以遍历每一个: for elem in s1.在您的情况下, pointNames 是字符串列表/数组 - 名称。所以你会做 s1 = set(names) 来获得唯一的飓风名称,然后循环。
  • 好的,在我的代码中,我已经有一个带有飓风名称的颜色字典 (color_dict)。根据我上面的代码,这是否正确:(我使用 n1 是因为我的代码中已经使用了名称)for n1, track in data.groupby('Name'): latitude = track.Lat.values longitude = track.Lon.values #Convert latitude and longitude to coordinates X and Y x, y = m(longitude, latitude) #Plot the points on the map pl.plot(x,y,'-', label=n1, color=colors_dict[n1])
猜你喜欢
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2021-04-12
相关资源
最近更新 更多