我试图用定制的颜色绘制一个shapefile,在地图上使用cartopy和matplotlib。
import numpy as np
import matplotlib.pyplot as plt
import cartopy as cartopy
import pandas as pd
import random as rd
def getcolor(buurtnaam):
a = rd.uniform(0.0, 255.0)
b = rd.uniform(0.0, 255.0)
c = rd.uniform(0.0, 255.0)
return tuple([a, b, c, 1])
ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.set_extent((5.35, 5.60, 51.4, 51.5), crs=cartopy.crs.PlateCarree())
filelocation=('buurt.shp')
reader = cartopy.io.shapereader.Reader(filelocation)
for label,shape in zip(reader.records(),reader.geometries()):
coordinates=cartopy.feature.ShapelyFeature(shape, cartopy.crs.PlateCarree(),edgecolor='black')
ax.add_feature(coordinates, facecolor=getcolor(label.attributes['buurtnaam']))
plt.show()然而,这会产生以下结果:
ValueError:无效的RGBA参数: 5.850575504984446
当我在for循环中打印RGBA值时,它们似乎是正确的。
print(label.attributes['buurtnaam'])罗丘布特
print (getcolor(label.attributes['buurtnaam']))(109.8833008320893,179.51867989390442,211.09771601504892,1)
print (type(getcolor(label.attributes['buurtnaam'])))类‘元组’
我的RGBA格式正确吗?这是cartopy/matplotlib中的错误吗?
发布于 2018-02-26 17:39:58
同时我解决了这个问题。RGBA元组应该包含0到1之间的4个值。
import numpy as np
import matplotlib.pyplot as plt
import cartopy as cartopy
import pandas as pd
import random as rd
def getcolor(buurtnaam):
a = rd.uniform(0.0, 1.0)
b = rd.uniform(0.0, 1.0)
c = rd.uniform(0.0, 1.0)
return tuple([a, b, c, 1])
ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.set_extent((5.35, 5.60, 51.4, 51.5), crs=cartopy.crs.PlateCarree())
filelocation=('buurt.shp')
reader = cartopy.io.shapereader.Reader(filelocation)
for label,shape in zip(reader.records(),reader.geometries()):
coordinates=cartopy.feature.ShapelyFeature(shape, cartopy.crs.PlateCarree(),edgecolor='black')
ax.add_feature(coordinates, facecolor=getcolor(label.attributes['buurtnaam']))
plt.show()发布于 2018-02-26 16:43:59
看起来,您的get_color函数正在生成与您的shapefile无关的随机数,并且这些数字用于您的RGB值。当您将属性buurtnaam的名称传递给函数时,您需要在RGB值生成中使用它。
https://stackoverflow.com/questions/48987682
复制相似问题