Altair repeat重复图表如何为各子图设置不同的子标题
Altair 重复图表设置差异化子标题实现方法
在基础图表的.properties()中配置title参数时,配置项会被所有重复生成的子图继承,因此会出现所有子图标题完全一致的效果:
Altair的repeat接口原生不支持直接传入标题列表批量为子图设置独立标题,可根据需求选择以下两种方案实现差异化子标题:
方案1:手动拼接子图(自由度最高,支持任意自定义标题)
放弃.repeat()自动生成子图的逻辑,手动遍历行、列维度的字段组合,为每个子图单独配置专属标题,最后通过横向、纵向拼接组合成和repeat效果一致的网格图,示例代码如下:
import altair as alt from vega_datasets import data iris = data.iris.url # 定义行列维度字段 row_fields = ['petalLength', 'petalWidth'] col_fields = ['sepalLength', 'sepalWidth'] # 按(行字段,列字段)的组合映射每个子图的自定义标题 sub_chart_titles = { ('petalLength', 'sepalLength'): '花瓣长度 vs 花萼长度', ('petalLength', 'sepalWidth'): '花瓣长度 vs 花萼宽度', ('petalWidth', 'sepalLength'): '花瓣宽度 vs 花萼长度', ('petalWidth', 'sepalWidth'): '花瓣宽度 vs 花萼宽度' } # 逐行生成子图并拼接 row_plot_list = [] for row_field in row_fields: col_plot_list = [] for col_field in col_fields: single_plot = alt.Chart(iris).mark_point().encode( x=alt.X(col_field, type='quantitative'), y=alt.Y(row_field, type='quantitative'), color='species:N' ).properties( width=200, height=200, title=sub_chart_titles[(row_field, col_field)] ) col_plot_list.append(single_plot) row_plot_list.append(alt.hconcat(*col_plot_list)) final_chart = alt.vconcat(*row_plot_list).interactive() final_chart
该方案没有标题规则限制,可自由设置每个子图的标题文案、样式,适配所有需要自定义子标题的场景。
方案2:基于repeat上下文表达式生成标题(适配标题与字段关联的场景)
如果差异化标题和子图对应的repeat字段存在映射关系,不需要设置完全无规则的独立文案,可以直接在repeat层配置标题规则,通过Vega表达式读取当前子图对应的行、列字段值自动生成标题,无需手动拼接子图,示例代码如下:
import altair as alt from vega_datasets import data iris = data.iris.url # 定义字段和显示名称的映射 field_name_map = { 'petalLength': '花瓣长度', 'petalWidth': '花瓣宽度', 'sepalLength': '花萼长度', 'sepalWidth': '花萼宽度' } alt.Chart(iris).mark_point().encode( alt.X(alt.repeat("column"), type='quantitative'), alt.Y(alt.repeat("row"), type='quantitative'), color='species:N' ).properties( width=200, height=200 ).repeat( row=['petalLength', 'petalWidth'], column=['sepalLength', 'sepalWidth'], # 用表达式读取当前子图的行列字段,拼接生成标题 title=alt.Title( expr=f"'Y轴:' + {field_name_map}[datum.row] + ' X轴:' + {field_name_map}[datum.column]" ) ).interactive()
注意:该方案依赖Vega表达式读取repeat上下文的
datum.row、datum.column值,只能生成和当前repeat字段关联的标题,无法实现完全无规则的自定义标题。
内容的提问来源于stack exchange,提问作者ITA
相关产品推荐
相关产品推荐

