将图表标题与 y 轴上数字的左侧对齐

Aligning chart title with left side of numbers on the y axis

我正在尝试制作符合我们内部指南的 Altair 主题。我发现这个出色的 article 解决了我的大部分问题。然而,无论是文章还是文档搜索都没有解决图表标题与 y 轴上数字左侧对齐的问题。 See the dotted line in Urban institute's theme for visual explanation。 问题是我不知道 y 轴上最长数字的宽度。我发现的解决方案只是为数字的预期宽度硬编码一个偏移量。但是,我必须制作一个在所有情况下都自动符合标准的主题。 欢迎提供可能解决方案的提示。我会试用它们并得到 post 结果。

此处列出了 Altair/Vega-Lite 的可用标题对齐设置:https://vega.github.io/vega-lite/docs/title.html#params

最接近你想要的是在标题配置中设置anchor='start'

import altair as alt
from vega_datasets import data
cars = data.cars()

alt.Chart(cars).mark_bar().encode(
  x=alt.X('Miles_per_Gallon', bin=True),
  y='count()',
).properties(
    title='A bar chart'
).configure_title(
    anchor='start'
)

不幸的是,Vega-Lite 模式中没有比这更精细地控制对齐方式的方法。如果这对您使用 Altair/Vega-Lite 很重要,我建议您打开一个 Vega-Lite feature request.

我不确定这是否正是您要找的,因为您提到要创建一个主题,但您可以通过 mark_text().

这是一个例子:

df = pd.DataFrame({'col1':[0,1,2,3,4,5], 'col2':[0,1,2,3,4,5]})
text_df = pd.DataFrame({'col1':[0], 'col2':[0], 'col3':['title']})

line = alt.Chart(df).mark_line().encode(x='col1', y='col2')
text = alt.Chart(text_df.query('col1 == 0')).mark_text(dx=-60, dy=-400, fontSize=24, font='Lato').encode(x='col1', y='col2', text='col3')
line + text

这是生成的图表: