![](/img/trans.png)
[英]How to create a choropleth map using mapbox and plotly at a country level?
[英]How to create square shaped legend markers while using geopandas to plot a choropleth map?
我正在嘗試創建一個具有方形標記而不是圓形標記的圖例。 我嘗試使用“.set_marker('s')”,它添加了多個標記。
這是我的代碼:
fig, ax = plt.subplots(figsize=(18, 10))
europe_gdf_without_russia.plot(
column="percentage_2nd_booster_60plus",
cmap='Blues',
legend=True,
legend_kwds={"title":"Percentage",
'loc':'center left',
"fmt": "{:.2f}%",
'bbox_to_anchor':(1,0.5),
},
edgecolor='black',
linewidth=0.8,
k=4,
scheme='quantiles',
missing_kwds={
"color": "lightgrey",
"label": "No data",
},
zorder=1,
ax=ax
)
# Customising the texts in the legend
leg = ax.get_legend()
for count, lbl in enumerate(leg.get_texts()):
label_text = lbl.get_text()
lowe1 = label_text.split()[0]
lower=lowe1.replace(',',' -')
upper = label_text.split()[1]
if count==0:
new_text = ' <{}'.format(upper)
else:
new_text = ' {} {}'.format(lower,upper)
lbl.set_text(new_text)
leg = ax.get_legend()
for ea in leg.legendHandles:
ea.set_marker('s')
獲得圖例句柄后,我嘗試使用“ea.set_marker('s')”。
這是我的代碼:
for ea in leg.legendHandles:
ea.set_marker('s')
我得到的 output:
我想為圖例的每一行獲得一個方形標記
在geopandas.plot()
中找不到legend_kwds
的關鍵字參數來解決問題。 盡管我以一種棘手的方式解決了這個問題。 訪問圖例后,我添加了以下代碼塊以獲得所需的結果。 我使用合適的位置點將圖例data
設置為一維數組。 在我的例子中是 (11.,3.85)。 此自定義數據點的目的是與 geopandas 的內置圖例標記重疊。 然后使 markersize 更大以完全重疊內置圖例標記並使用lh._legmarker.set_markeredgecolor('None')
刪除內置邊緣標記顏色。 這是新的代碼塊:
for lh in leg.legendHandles:
lh.set_marker('s')
lh.set_data((11.5,3.85))
lh.set_markersize(17)
lh.set_markeredgecolor("None")
lh._legmarker.set_markeredgecolor('None')
這是完整代碼的最終版本:
fig, ax = plt.subplots(figsize=(18, 10))
europe_gdf_without_russia.plot( column="percentage_2nd_booster_60plus",
cmap='Blues',
legend=True,
legend_kwds={"title":"Percentage",
"loc":"center left",
"fmt": "{:.2f}%",
"bbox_to_anchor":(1,0.5),},
edgecolor='black',
linewidth=0.8,
k=4,
scheme='quantiles',
missing_kwds={"color": "lightgrey",
"label": "No data"},
zorder=1,
ax=ax)
leg = ax.get_legend()
for lh in leg.legendHandles:
lh.set_marker('s')
lh.set_data((11.5,3.85))
lh.set_markersize(17)
lh.set_markeredgecolor("None")
lh._legmarker.set_markeredgecolor('None')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.