简体   繁体   中英

Changing Size of Legend in Altair

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM