I'm loving Altair for creating choropleth maps! My biggest problem, however, is I cannot figure out how to change the size of the legend. I've read through the documentation and tried several things to no avail.
Here's an example using the unemployment map by county from Altair's docs. I added a 'config' layer to change the font size for the title on both the map and the legend. Note the .configure_legend() part of the code within "config".
counties = alt.topo_feature(data.us_10m.url, 'counties')
source = data.unemployment.url
foreground = alt.Chart(counties).mark_geoshape(
).encode(
color=alt.Color('rate:Q', sort="descending", scale=alt.Scale(scheme='plasma'), legend=alt.Legend(title="Unemp Rate", tickCount=6))
).transform_lookup(
lookup='id',
from_=alt.LookupData(source, 'id', ['rate'])
).project(
type='albersUsa'
).properties(
title="Unemployment Rate by County",
width=500,
height=300
)
config = alt.layer(foreground).configure_title(fontSize=20, anchor="middle").configure_legend(titleColor='black', titleFontSize=14)
config
Here's what the image should look like:
If I change the size of the map like this:
counties = alt.topo_feature(data.us_10m.url, 'counties')
source = data.unemployment.url
foreground = alt.Chart(counties).mark_geoshape(
).encode(
color=alt.Color('rate:Q', sort="descending", scale=alt.Scale(scheme='plasma'), legend=alt.Legend(title="Unemp Rate", tickCount=6))
).transform_lookup(
lookup='id',
from_=alt.LookupData(source, 'id', ['rate'])
).project(
type='albersUsa'
).properties(
title="Unemployment Rate by County",
width=900,
height=540
)
config = alt.layer(foreground).configure_title(fontSize=20, anchor="middle").configure_legend(titleColor='black', titleFontSize=14)
config
The legend stays the same size, so that it now looks tiny in comparison to the map:
Alternatively, if I make the map size tiny, the legend will be huge!
I've tried about a dozen different things to no avail.
Anyone have a solution to this?
As you have seen, the legend has a default size in pixels that is constant regardless of the size of the chart. If you would like to adjust it, you can use the configure_legend()
chart method.
In Altair 3.0 or later, the following arguments are the relevant ones for adjusting the size of the legend gradient:
chart.configure_legend(
gradientLength=400,
gradientThickness=30
)
The first answer is super close but missing the most important piece for changing the font size in the legend. Use the code snippet below to adjust font size of text in the legend.
.configure_legend(
titleFontSize=18,
labelFontSize=15
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With