![](/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.