在Altair中更改图例的大小

9

我喜欢使用Altair来创建区域地图,但是我遇到的最大问题是我无法弄清楚如何改变图例的大小。我已经阅读了文档并尝试了几种方法,但都没有成功。

以下是一个使用Altair文档中的县级失业地图的示例。我添加了一个“config”层,用于同时更改地图和图例标题的字体大小。请注意,“config”中的代码部分包括“.configure_legend()”。

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

这是图像应该呈现的样子: enter image description here 如果我改变地图的大小,它会变成这样:
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

图例大小没有改变,因此与地图相比现在看起来非常小:

enter image description here

另一种选择是缩小地图尺寸,这样图例就会非常大!

enter image description here

我已经尝试了约十几种不同的方法,但都无济于事。
有人有解决方案吗?
2个回答

10

正如您所见,图例在像素上有一个默认大小,无论图表的大小如何都是恒定的。如果您想要进行调整,可以使用configure_legend()图表方法。

在Altair 3.0或更高版本中,以下参数是调整图例渐变大小的相关参数:

chart.configure_legend(
    gradientLength=400,
    gradientThickness=30
) 

谢谢,jakevdp。这个问题在3.0中最近修复了吗?我相当确定我曾经在2.4中尝试过gradientHeight和gradientWidth,但是它不起作用,但这段代码在3.0中确实有效。然而,看起来其他各种事情也发生了变化。例如,现在颜色方案看起来非常不同 :) - Ragnar Lothbrok
1
图例是从 Vega-Lite 2 到 3 的重大变化之一:现在有创建水平和垂直图例的选项,配置选项也已更新并相应地更名。 - jakevdp

4
第一个答案非常接近,但缺失了更改图例字体大小的最重要部分。请使用下面的代码片段来调整图例中文本的字体大小。

.configure_legend(
titleFontSize=18,
labelFontSize=15
) 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接