配置 Altair 图表的标题和轴

p_m*_*_mo 4 data-visualization altair grouped-bar-chart

我最近正在学习如何使用 Altair 创建图表,但在自定义标题和轴时遇到了一些问题。我的图表代码目前如下所示:

chart = Chart(data).mark_bar().encode(
    column='Cell Type',
    x='Truth/Pred',
    y='03',
    color='Truth/Pred',
).properties(
    title='Truth vs Predictions for Cell Type Percentages'
).configure_axisBottom(
    disable = True
).configure_axisTop(
    # labelPadding = 100
    orientation = "bottom"
).configure_axisY(
    title = "Cell Type Percentages"
)

chart.display()
Run Code Online (Sandbox Code Playgroud)

图表如下所示: 由上面的代码生成的图表

我有几个问题。

有没有办法让标题居中?

其次,我试图将 Y 轴设置为“单元格类型百分比”,但似乎没有 Y 轴,我不确定为什么。

最后,我尝试将顶部轴移至底部,并将标签稍微隔开一点,或旋转它们,使它们不会彼此重叠。然而,配置 axisTop 参数似乎根本不影响 Cell Type 轴!我也不确定为什么会这样。

我尝试遵循此堆栈溢出问题的答案:链接到相关问题

但我总是收到错误说明"additional properties are not allowed",所以我不确定他们是否停止在构造函数中使用配置属性。

任何帮助表示赞赏。谢谢你!

joe*_*lom 5

由于 Vega-Lite 错误https://github.com/vega/vega-lite/issues/5547 ,标题对齐存在一些问题。但是,以下代码片段应该可以完成您想要的大部分操作:

import altair as alt
from vega_datasets import data


source = data.barley

# Create a centered title
title = alt.TitleParams('A centered title', anchor='middle')
alt.Chart(source.url, title=title).mark_bar().encode(
    x=alt.X('year:O', title=''),
    # It is usually easier to specify custom titles like this
    y=alt.Y('sum(yield):Q', title='My custom Y title'),
    color=alt.Color('year:N', title=''),
    # Changing the header of the faceted column controls label location
    column=alt.Column('site:N', title='', header=alt.Header(labelOrient='bottom', labelAngle=-45, labelAlign='right'))
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述