将图例添加到Altair的分层图表中 [英] Adding legend to layerd chart in altair
问题描述
请考虑以下示例:
导入altair为alt从vega_datasets导入数据df = data.seattle_weather()temp_max = alt.Chart(df).mark_line(color ='blue').encode(x ='yearmonth(date):T',y ='max(temp_max)',)temp_min = alt.Chart(df).mark_line(color='red').encode(x ='yearmonth(date):T',y ='max(temp_min)',)temp_max + temp_min
在生成的图表中,我想添加一个图例,该图例显示蓝线显示最高温度,红线显示最低温度.最简单的方法是什么?
我看到了(例如,在该问题的解决方案中:
Consider the following example:
import altair as alt
from vega_datasets import data
df = data.seattle_weather()
temp_max = alt.Chart(df).mark_line(color='blue').encode(
x='yearmonth(date):T',
y='max(temp_max)',
)
temp_min = alt.Chart(df).mark_line(color='red').encode(
x='yearmonth(date):T',
y='max(temp_min)',
)
temp_max + temp_min
In the resulting chart, I would like to add a legend that shows, that the blue line shows the maximum temperature and the red line the minimum temperature. What would be the easiest way to achieve this?
I saw (e.g. in the solution to this question: Labelling Layered Charts in Altair (Python)) that altair only adds a legend if in the encoding, you set the color or size or so, usually with a categorical column, but that is not possible here because I'm plotting the whole column and the label should be the column name (which is now shown in the y-axis label).
I would do a fold transform such that the variables could be encoded correctly.
import altair as alt
from vega_datasets import data
df = data.seattle_weather()
alt.Chart(df).mark_line().transform_fold(
fold=['temp_max', 'temp_min'],
as_=['variable', 'value']
).encode(
x='yearmonth(date):T',
y='max(value):Q',
color='variable:N'
)
这篇关于将图例添加到Altair的分层图表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!