python-3.x 如何向Altair生成的图表添加副标题

qyzbxkaa  于 2022-12-15  发布在  Python
关注(0)|答案(3)|浏览(140)

看起来你还不能在使用Altair Python库制作的图表上给标题添加副标题。

我喜欢牛郎星,但是根据我发现的线索,牛郎星没有为图表添加字幕的能力。有人知道如何添加字幕吗?我想到了换行符,但是看起来对它的支持仍然被添加到织女星/织女星精简版,这是牛郎星的基础。
这里是我认为可以在这个狭窄的问题上找到的所有东西...
以下是牛郎星团队说这是织女星的问题:
https://github.com/altair-viz/altair/issues/987
下面是Vega团队说它还没有修复(我认为):
https://github.com/vega/vega-lite/issues/4055

如果你能找到任何方法来添加一个副标题到标题或轴标签,这将是巨大的!!

oyjwcjzk

oyjwcjzk1#

关于altair/vega-lite/vega生态系统最好的事情之一就是它是多么的活跃。自从上次发布以来,整个工具链(特别是this pr)已经有了一些开发,这些开发已经解决了这个问题!!
除了多行字幕外,该更改还增加了对标题的多行支持。示例代码片段:

import altair as alt
from vega_datasets import data

chart = alt.Chart(data.cars.url).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
).properties(
    title={
      "text": ["First line of title", "Second line of title"], 
      "subtitle": ["Cool first line of subtitle", "Even cooler second line wow dang"],
      "color": "red",
      "subtitleColor": "green"
    }
)
chart

其结果为:

e4eetjau

e4eetjau2#

Altair不支持字幕,因为渲染Altair图表的Vega-Lite库不支持字幕。
也就是说,如果你愿意的话,你可以使用图表连接来拼凑一些类似于副标题的东西。

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

title = alt.Chart(
    {"values": [{"text": "The Title"}]}
).mark_text(size=20).encode(
    text="text:N"
)

subtitle = alt.Chart(
    {"values": [{"text": "Subtitle"}]}
).mark_text(size=14).encode(
    text="text:N"
)

chart = alt.Chart(cars).mark_point().encode(
  x='Horsepower',
  y='Miles_per_Gallon',
  color='Origin'
)

alt.vconcat(
    title,
    subtitle,
    chart
).configure_view(
    stroke=None
).configure_concat(
    spacing=1
)

eyh26e7m

eyh26e7m3#

您还可以使用alt.TitleParams而不是手动创建字典,并直接在Chart中设置标题而不是使用.properties方法:

import altair as alt
from vega_datasets import data

chart_title = alt.TitleParams(
    "Main figure title",
    subtitle=["First line that will not wrap no matter how much text it has", "Second line"],
)
alt.Chart(data.cars.url, title=chart_title).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q'
)

如果你打印变量chart_title,你会看到它包含了一个字典,和mcnutt前面的答案中使用的字典相似。

TitleParams({
  subtitle: ['First line that will not wrap no matter how much text it has', 'Second line'],
  text: 'Main figure title'
})

您还可以使用此技术在图表下添加类似标题的元素:

chart_title = alt.TitleParams(
    "Main figure title",
    subtitle=["First line that will not wrap no matter how much text it has", "Second line"],
    anchor='start',
    orient='bottom',
    offset=20
)
alt.Chart(data.cars.url, title=chart_title).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q'
)

如果我们想创建一个长的标题,手动将字符串格式化为列表会非常繁琐,我们可以使用textwrap库:

from textwrap import wrap

# Inside alt.TitleParams
subtitle=wrap("First line that will not wrap no matter how much text it has unless we convert it to a list first", 40),

相关问题