[英]python: how to generate a json file with polygons of the same color but different opacities
我正在使用python生成一個包含許多多邊形的json文件,並且為每個多邊形分配了一個值,如下所示:
[{'cell':{'type':'Polygon', 'coordinates':[[[121,47],[122,48],[122,47],[121,47]]]}, 'value':2.45},
{'cell':{'type':'Polygon', 'coordinates':[[[120,48],[123,48.5],[122,48],[120,48]]]}, 'value':1.45},
...]
我想在geojson.io上繪制這些多邊形,每個單元格都是紅色。 但是每個多邊形的不透明度取決於值,值越高,不透明度越高; 值越小,不透明性越小。
我認為我應該首先對所有值進行歸一化,然后再使用
Feature(properties={'fill':'#ff0000', 'opacity':normalized_value})
但是我認為這有點復雜。 我可以只對屬性中的每個單元格使用原始值,不透明度會自動調整嗎?
所以我去了geojson.io 。 我得到:
{
"type": "Feature",
"properties": {
"stroke": "#555555",
"stroke-width": 2,
"stroke-opacity": 1,
"fill-opacity": 0.67,
"fill": "#ff0000"
},
"geometry": {
"type": "Polygon",
"coordinates": []
}
}
我現在忽略了坐標,因為它們占用了太多空間。 首先讓我們做一個小類,返回一個字典。 它必須具有的設置,顏色和不透明度。
class Polygon:
def __init__(self, opacity, coordinates):
self.opacity = opacity
self.fill = "#ff0000"
c=coordinates
coordinates = [[
c[0],
c[1],
c[2],
c[3],
c[0]
]]
self.coordinates = coordinates
def json(self):
return {
"type": "Feature",
"properties": {
"fill-opacity": self.opacity,
"fill": self.fill
},
"geometry": {
"type": "Polygon",
"coordinates": self.coordinates
}
}
features = [Polygon(random.random(), rand_coords()) for i in range(10)]
print(json.dumps({
"type": "FeatureCollection",
"features": [i.json() for i in features]
}))
如果您希望能夠使用單元格格式。 你可以這樣做。
cell_list = [
{'cell':{'type':'Polygon',
'coordinates':[[[121,47],[122,48],[122,47],[121,47]]]}, 'value':2.45},
{'cell':{'type':'Polygon',
'coordinates':[[[120,48],[123,48.5],[122,48],[120,48]]]}, 'value':1.45}
]
#get a list of polygons.
features = [
Polygon(cell['value'], cell['cell']['coordinates'][0]) for cell in cell_list
]
#largest value
max_opacity = max(feature.opacity for feature in features)
#normalise
for feature in features:
feature.opacity /= max_opacity
#get the compatible json data
print(json.dumps({
"type": "FeatureCollection",
"features": [i.json() for i in features]
}, sort_keys=True, indent=4, separators=(',', ': ')))
這不是最佳的工作系統。 當我執行它並復制輸出時,我得到了位於中國右上角的三角形。但是三角形的不透明度是不同的。
我並沒有對形狀做任何事情,因為沒有要求。 但是,我可以將輸入更改為有效輸出。 全紅色,相對不透明。
您可以在這里檢查它是否還好。 但是,將鼠標懸停在形狀上可以查看設置。 礦山呈藍色,顏色設置為“#ff0000”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.