如何解决您如何使用scipy.spatial的Voronoi包选择自定义颜色来填充Voronoi图的区域?
我有一个代码,可读取包含位置,其经度和纬度以及是否曾经去过的CSV文件(用“ Y”或“ N”标记)。我想在Voronoi图中展示它,但至关重要的是,我想根据以下标准为区域着色:
- 如果我没去过('N'),请将区域标记为白色
- 如果我去过('Y')标记区域,则该颜色为地图上其他任何颜色所独有的随机颜色
我的代码有两个问题:我似乎无法将Voronoi(coords)
产生的区域与我的原始位置列表进行匹配(因此,我无法轻易将区域与我要填充的颜色相对应)该区域,因为定义和填充区域的顺序不是它们在数据帧中出现的顺序),其次,如何确保每种随机颜色是“唯一的”,即在每种颜色中出现的颜色都不相同地区。
我相当确定可以找到第二个问题的解决方案,这是我正在努力解决的第一个问题。任何帮助将非常感激。这是我的代码:
import pandas as pd
from scipy.spatial import Voronoi,voronoi_plot_2d
import numpy as np
# read places,with lat and lon
places = pd.read_csv("places.csv")
# convert subset to numpy array
coords = places[['Longitude','Latitude']].values
# add 4 distant dummy points
coords = np.append(coords,[[999,999],[-999,[999,-999],-999]],axis = 0)
colours = np.append(places[['Been']].values,[['N'],['N'],['N']],axis = 0).flatten()
colours = np.insert(colours,['N','N'])
# assign a random colour to the array if visited,leave white if not
colours[colours == 'N'] = 'w'
import random
r = lambda: random.randint(0,255)
colours[colours == 'Y'] = '#%02X%02X%02X' % (r(),r(),r())
print(places['Place'])
print(colours)
print(coords)
# compute voronoi tesselation
vor = Voronoi(coords)
# plot voronoi diagram
import matplotlib.pyplot as plt
fig = voronoi_plot_2d(vor,show_vertices = False)
j = -1
# colourise the regions
for region in vor.regions:
j = j+1
print(region)
if not -1 in region:
polygon = [vor.vertices[i] for i in region]
plt.fill(*zip(*polygon),colours[j])
# fix the range of axes,plot locations
plt.plot(coords[:,0],coords[:,1],'ko')
plt.xlim([places['Longitude'].min() - 0.6,places['Longitude'].max() + 0.6]),plt.ylim([places['Latitude'].min() - 0.6,places['Latitude'].max() + 0.6])
# annotate each point with the place name
[plt.annotate(places['Place'][i],(coords[i,coords[i,1]),xytext=(coords[i,0]-0.2,1]+0.2)) for i in range(len(places))]
plt.show()
我已经在Jupyter Notebooks中制作了这个。我的csv文件如下所示:
Place,Latitude,Longitude,Been
Bern,46.948,7.4474,N
Juras,47.0086,6.7856,N
Lake Como,46.016,9.2572,N
Lyon,45.764,4.8357,N
Marseille,43.2965,5.3698,N
Milan,45.4642,9.19,N
Monaco,43.7384,7.4246,N
Mont Blanc,45.8326,6.8652,N
Mont Saleve,46.0942,6.1403,Y
Munich,48.1351,11.582,N
Turin,45.0703,7.6869,N
Zurich,47.3769,8.5417,N
如果有帮助,我会保留在打印语句中,并在测试中添加一些注释的代码行。我目前正在为Lyon标记的区域着色,这说明了我不知道如何使用region in vor.regions
来检索其对应坐标的问题。预先感谢。
解决方法
您需要使用所得Voronoi结果的point_region属性来确定哪个输入点与哪个Voronoi区域相对应。这是更新的代码,为显示的区域着色。
我更新了代码,为每个彩色Voronoi区域提供了不同的随机颜色。这是代码:
import pandas as pd
from scipy.spatial import Voronoi,voronoi_plot_2d
import numpy as np
# read places,with lat and lon
places = pd.read_csv("places.csv")
# convert subset to numpy array
coords = places[['Longitude','Latitude']].values
# add 4 distant dummy points
coords = np.append(coords,[[999,999],[-999,[999,-999],-999]],axis = 0)
colourFlag = np.append(places[['Been']].values,[['N'],['N'],['N']],axis = 0).flatten()
# assign a random colour to the array if visited,leave white if not
import random
r = lambda: random.randint(0,255)
colours = list(map(lambda flag: '#%02X%02X%02X' % (r(),r(),r()) if (flag == 'Y') else 'w',colourFlag))
# compute voronoi tesselation
vor = Voronoi(coords)
# plot voronoi diagram
import matplotlib.pyplot as plt
fig = voronoi_plot_2d(vor,show_vertices = False)
for j in range(len(coords)):
region = vor.regions[vor.point_region[j]]
if not -1 in region:
polygon = [vor.vertices[i] for i in region]
plt.fill(*zip(*polygon),colours[j])
# fix the range of axes,plot locations
plt.plot(coords[:,0],coords[:,1],'ko')
plt.xlim([places['Longitude'].min() - 0.6,places['Longitude'].max() + 0.6]),plt.ylim([places['Latitude'].min() - 0.6,places['Latitude'].max() + 0.6])
# annotate each point with the place name
[plt.annotate(places['Place'][i],(coords[i,coords[i,1]),xytext=(coords[i,0]-0.2,1]+0.2)) for i in range(len(places))]
plt.show()
这是我制作的一个绘图,在原始文件的某些行中添加了颜色:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。