使用for循环从csv文件中的不同纬度和经度坐标制作线的cartopy图

Using a for loop to make a cartopy plot of lines from different latitude and longitude coordinates from a csv file

我的代码的目标是使用宾夕法尼亚州收费公路上出口的纬度和经度绘制一个粗略的路线图,在每个出口之间画一条线。

每次循环时,我都在使用 for 循环在地图上绘制一条线。如果我对纬度和经度进行硬编码,这会起作用,但是一旦我插入我的变量,就不会绘制任何东西。由于坐标是有序的,我只是在每次循环获取下一个坐标时增加索引。我已经在循环中打印了变量并验证它们具有所需的值。我试过将值按顺序排列,但绘图函数不喜欢我使用 nparrays。我不确定我是否遗漏了一些简单的东西,但我很感激任何输入。

import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
from datetime import datetime, timedelta

# Open the file for highway metadata to read csv data
highway_metadata = open('milestone3data.csv', 'r')
metafile = csv.reader(highway_metadata, delimiter = ',')

# Create empty lists with highway data
highway_loc = []
highway_name = []
highway_lat = []
highway_lon = []
highway_dist = []

# Loop to transfer the csv file's data into the lists
for i in metafile:
    highway_loc.append(i[0])
    highway_name.append(i[1])
    highway_lat.append(float(i[2]))
    highway_lon.append(float(i[3]))
    highway_dist.append(i[4])

def road_map():

    enhighway_lat = enumerate(highway_lat)
    enhighway_lon = enumerate(highway_lon)
    orthographic = ccrs.Orthographic()
    platecarree = ccrs.PlateCarree()
    proj = ccrs.Orthographic(central_longitude = -75, central_latitude = 41)
    ax = plt.axes(projection=proj)
  # Set up the background
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.add_feature(cartopy.feature.STATES)
    ax.set_extent((-85,-70,36,45),crs=ccrs.PlateCarree())

    for i,j in enhighway_lat:
        for k,l in enhighway_lon:
            if i or k <= 30:
                plt.plot([highway_lon[k], highway_lon[k+1]], [highway_lat[i], highway_lat[i+1]], color='black', linewidth=1, marker='o', markersize=3, transform=ccrs.PlateCarree())

    plt.savefig('cartopytest7.png')
    plt.show
road_map()

[This is my most recent output from the program][1]

  [1]: https://i.stack.imgur.com/lgFrN.png

CSV 文件内容:(英里标记、出口名称、纬度、经度、距收费公路起点的英里数)

2,Gateway (Ohio Connection),40.90419167,-80.47158333,1.43
10,New Castle,40.83018056,-80.34196111,10.7
13,Beaver Valley,40.8143,-80.307925,12.87
28,Cranberry,40.67983889,-80.09537778,28.47
30,Warrendale,40.65533889,-80.06116667,31
39,Butler Valley,40.60913611,-79.91924444,39.1
48,Allegheny Valley,40.542025,-79.81022222,47.73
57,Pittsburgh,40.43808889,-79.74956944,56.44
67,Irwin,40.31342778,-79.65476111,67.22
75,New Stanton,40.22173333,-79.59573333,75.39
91,Donegal,40.10915,-79.35231944,90.69
110,Somerset,40.02033056,-79.05208056,109.91
146,Bedford,40.05013889,-78.48615,145.5
161,Breezewood,39.98721667,-78.24472778,161.5
180,Fort Littleton,40.05010556,-77.93954444,179.44
189,Willow Hill,40.09674167,-77.78441389,188.59
201,Blue Mountain,40.15755278,-77.58403333,201.29
226,Carlisle,40.22814722,-77.14782222,226.54
236,Gettysburg Pike,40.19569444,-76.95665556,236.22
242,Harrisburg West Shore,40.21216667,-76.85765278,241.87
247,Harrisburg East,40.21501111,-76.78060278,247.38
266,Lebanon-Lancaster,40.22974444,-76.43095,266.45
286,Reading,40.21805,-76.05189167,286.09
298,Morgantown,40.15990278,-75.88311667,298.33
312,Downingtown,40.06838611,-75.66450278,311.93
320,SR29,40.07641667,-75.52881944,319.33
326,Valley Forge,40.09296667,-75.39591111,326.62
333,Norristown,40.11101111,-75.27921389,333.28
339,Fort Washington,40.13231944,-75.17092222,338.36
340,Virginia Dr,40.13854444,-75.16268611,339.8
343,Willow Grove,40.16166111,-75.11271111,342.91
351,Bensalem,40.13200278,-74.96229444,351.49
352,Street Rd,40.13150833,-74.96445,351.89
353,Neshaminy Falls,40.12916667,-74.94150278,352.67

好的,基于上面的讨论,请看下面的解决方案。

备注:

  • 我正在使用 pandas DataFames 轻松处理 .csv 文件。 names 字段是列名。
  • 我根本没有使用正交投影。
  • 我正在遍历高速公路出口列表,一次一个出口;在每个索引处,我正在提取当前和下一个出口的数据 - 我确信还有更多 'pythonic' 方法可以做到这一点,但这至少是可读的。
  • 编辑:循环中的最终索引是长度-1
  • 更新:感谢@SimonWillerton,我删除了循环。
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import pandas as pd

def road_map():    
    # Open the file for highway metadata to read csv data
    highway_metadata = pd.read_csv('milestone3data.csv', names=["loc", "name", "lat", "lon", "dist"])

    proj = ccrs.PlateCarree(central_longitude = -75)
    ax   = plt.axes(projection=proj)
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.add_feature(cartopy.feature.STATES)
    ax.set_extent((-85,-70,36,45),crs=ccrs.PlateCarree())
    
    plt.plot(highway_metadata['lon'], highway_metadata['lat'], \
             color='black', linewidth=1, marker='o', markersize=3, transform=ccrs.PlateCarree())
                       
    plt.savefig('cartopytest7.png')

if __name__ == '__main__':
    road_map()

这将生成以下图像:

而且,根据这张来自维基百科的宾夕法尼亚收费公路图片(来源=https://commons.wikimedia.org/wiki/File:Pennsylvania_Turnpike_map.svg#file),我认为我们取得了成功

您的 plt.plot() 语句似乎试图做一些相当复杂的事情。您有经度列表和纬度列表;这就是在 matplotlib 中的点之间绘图所需的全部,不需要 enumerate 或循环列表。下面一行应该可以解决问题。

plt.plot(highway_lon, highway_lat, color='black', linewidth=1, marker='o', markersize=3, transform=ccrs.PlateCarree())

这是删除了一些不必要位的代码。

import csv
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs

# Open the file for highway metadata to read csv data
highway_metadata = open('milestone3data.csv', 'r')
metafile = csv.reader(highway_metadata, delimiter = ',')

# Create empty lists with highway data
highway_loc = []
highway_name = []
highway_lat = []
highway_lon = []
highway_dist = []

# Loop to transfer the csv file's data into the lists
for i in metafile:
    highway_loc.append(i[0])
    highway_name.append(i[1])
    highway_lat.append(float(i[2]))
    highway_lon.append(float(i[3]))
    highway_dist.append(i[4])

def road_map():
    fig = plt.figure(figsize=(10, 10))
    proj = ccrs.Orthographic(central_longitude = -75, 
                             central_latitude = 41)
    ax = plt.axes(projection=proj)
    ax.set_extent((-85,-70,36,45),crs=ccrs.PlateCarree())
    # Set up the background
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.add_feature(cartopy.feature.STATES)

    plt.plot(highway_lon, highway_lat, 
             color='black', linewidth=1, marker='o', markersize=3, 
             transform=ccrs.PlateCarree())

    plt.savefig('cartopytest7.png')
    plt.show
    
road_map()