独立于图例Python处理绘图(?)中的数据

2024-09-30 22:15:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们从一个经常更改值的源中导入shapefile。其中一个shapefile包含1到5之间的值,但大小和值不同(例如,第一次从源抓取shapefile时,它包含1个值)。下一次从源抓取时,它包含4个值)另一个shapefile包含动物名称,但只有3种可能,就像第一个shapefile一样,它的值可以不同

假设shapefile1包含“2”和“3”,而当我们第一次获取zip文件时,shapefile2包含“Horse”。在图例中,我只希望“2”、“3”和“Horse”以正确的图标显示(请参见下面的脚本)。下次运行程序并获取zip文件夹时,shapefile1包含“1”、“2”、“4”、“5”,shapefile2包含“Bird”、“Cat”。图例应该有“1”、“2”、“4”、“5”、“Bird”、“Cat”

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import requests, zipfile, io

def plot_stuff_sf1(x, y, color):
    m.plot(x, y, c = color, mec = 'k', m = 'o', ms = 5., ls = None, mew = 1.)

def plot_stuff_sf2(x, y, marker):
    m.plot(x, y, color = 'c', mec = 'k', m = marker, ms = 5., ls = None, mew = 1.)

#gets zipped file and stores on computer
zip_file_url = 'zippedfile/location'
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall('/path/to/save/files')

m = Basemap(projection = 'merc', llcrnrlat= 90, urcrnrlat= -90,
             llcrnrlon= -180, urcrnrlon= 180, lat_ts=40,resolution='i') 
m.readshapefile('/path/to/shapefile', 'name')
points_info = m.readshapefile('/path/to/shapefile', 'name')
for info, shape in zip(m.name_info, m.name):
    x, y = zip(shape)
    if info['NUMBER'] == '1':
        plot_stuff_sf1(x, y, 'c')
    elif info['NUMBER'] == '2':
        plot_stuff_sf1(x, y, 'm')
    elif info['NUMBER'] == '3':
        plot_stuff_sf1(x, y, 'g')
    elif info['NUMBER'] == '4':
        plot_stuff_sf1(x, y, 'r')
    elif info['NUMBER'] == '5':
        plot_stuff_sf1(x, y, 'k')

m.readshapefile('/path/to/shapefile2', 'name2')
name_info2 = m.readshapefile('/path/to/shapefile2', 'name2')
for info, shape in zip(m.name_info2, m.name2):
    x, y = zip(shape)
    if info['VALUE'] == 'Bird':
        plot_stuff_sf2(x, y, 'o')
    elif info['VALUE'] == 'Horse':
        plot_stuff_sf2(x, y, 'D')
    elif info['VALUE'] == 'Cat':
        plot_stuff_sf2(x, y, '>')

我没有包括图例代码,因为那是我被绊倒的地方。我查看了文档并尝试了plt.legend(handles = [...]),但由于某些原因,它没有起作用(甚至当我从文档中复制/粘贴代码并将其与脚本集成时)


Tags: topathnameinfonumberplotzipshapefile