我正在尝试绘制一张荷兰的地图,其中各省都充满了一些色彩。我一直在向this SO post和this blog post寻求帮助和代码示例。除非他们使用
lines = LineCollection(shpsegs,antialiaseds=(1,))
lines.set_facecolors(cm.jet(np.random.rand(1)))
用给定的颜色填充形状,这对我没有任何帮助。我不知道为什么它没有为我做任何事情。这并没有给我一个错误,而且我也看不到任何颜色。
我非常感谢您的帮助。我的(几乎)整个代码都在下面,我剪掉了一些不必要的部分:
import shapefile
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.collections import LineCollection
import numpy as np
##Importing shapefile and records
sf = shapefile.Reader("NLadmin/NLD_adm1")
records = sf.records()
for i in range(len(records)):
print(str(i) + " - " + str(records[i][4]))
shapes = sf.shapes()
for i in range(len(shapes)):
print(shapes[i].parts)
##Figure
fig = plt.figure()
ax = plt.axes()
ax.set_aspect(1.1541)
ax.set_xlim(3, 7.5)
ax.set_ylim(50.5, 54)
print("-------")
##Use the shapes and records
for shape, record in zip(list(sf.iterShapes()), records):
number_points = len(shape.points)
number_parts = len(shape.parts)
for index in range(number_parts):
startindex = shape.parts[index]
if index < len(shape.parts)-1:
endindex = shape.parts[index+1]
else:
endindex = number_points
shapesegment = shape.points[startindex:endindex]
x_lon = []
y_lat = []
for index in range(len(shapesegment)):
x_lon.append(shapesegment[index][0])
y_lat.append(shapesegment[index][1])
linelist = []
for i in range(len(x_lon)):
intermediatelist = []
try:
startxy = (x_lon[i], y_lat[i])
endxy = (x_lon[i+1], y_lat[i+1])
except:
continue
intermediatelist.append(startxy)
intermediatelist.append(endxy)
linelist.append(intermediatelist)
lines = LineCollection(linelist,antialiaseds=(1,))
lines.set_facecolors('#e41a1c')
lines.set_edgecolors('k')
lines.set_linewidth(1)
ax.add_collection(lines)
plt.show()