I am trying create a legend which will have square shaped markers instead of round markers. I tried to use ".set_marker('s')" and it is adding multiple markers.
Here is my code:
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')
I tried to use "ea.set_marker('s')" after getting the legendhandles.
Here is my code:
for ea in leg.legendHandles:
ea.set_marker('s')
And the output I am getting:
I want to get a single square shape marker for each line of the legend
CodePudding user response:
Couldn't find a keyword argument for legend_kwds
in geopandas.plot()
to solve the issue. Though I solved this in a tricky way. After accessing the legend I added the following chunk of code to get the required result. I set the data
of the legend to 1d array using the suitable positional point. In my case it was (11.,3.85). The purpose of this customise data point is to overlap the built-in legend marker from geopandas. Then make the markersize bigger to fully overlap the built-in legend marker and used lh._legmarker.set_markeredgecolor('None')
to remove the built-in edge marker colour. Here is the new chunk of code:
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')
Here is the final version of the full code:
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')