消除具有共享轴的两个图形之间的间隙

问题描述 投票:0回答:1

目标

我想生成一个“双端”条形图,显示获得的分数(某些指标)与错过的分数,如下所示:

graph I want to make

目前的结果

我成功做到了这一点

import altair as alt
import pandas as pd

source = pd.DataFrame(
    {
        "cohort": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
        "gained": [28, 55, 43, 91, 81, 53, 19, 87, 52],
        "missed": [5, 8, 34, 21, 16, 22, 9, 7, 11],
    }
)

up = (
    alt.Chart(source)
    .mark_bar(color="blue")
    .encode(
        x=alt.X("cohort:N").axis(labels=False, title=None, ticks=False),
        y=alt.Y("gained:Q"),
    )
)
down = (
    alt.Chart(source)
    .mark_bar(color="red")
    .encode(
        x=alt.X("cohort:N").axis(labelAngle=0),
        y=alt.Y("missed:Q", scale=alt.Scale(reverse=True)),
    )
)

alt.vconcat(up, down).resolve_scale(x="shared")

生成此: results so far

有什么办法可以消除间隙吗?或者也许用 Vega-Altair 来完全不同地解决这个问题?

python visualization altair
1个回答
0
投票

对于Altair,我没有太多经验。您要找的图表是参考中的垂直金字塔图吗?如果是这样,我会在中间添加一个 x 轴。将图形之间的间距设置为 0。

import altair as alt
import pandas as pd

source = pd.DataFrame(
    {
        "cohort": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
        "gained": [28, 55, 43, 91, 81, 53, 19, 87, 52],
        "missed": [5, 8, 34, 21, 16, 22, 9, 7, 11],
    }
)

up = (
    alt.Chart(source)
    .mark_bar(color="blue")
    .encode(
        x=alt.X("cohort:N").axis(None),
        y=alt.Y("gained:Q"),
    )
)
middle = alt.Chart(source).encode(
    alt.X('cohort:N').axis(None),
    alt.Text('cohort:N'),
).mark_text().properties(height=15)

down = (
    alt.Chart(source)
    .mark_bar(color="red")
    .encode(
        x=alt.X("cohort:N").axis(None),
        y=alt.Y("missed:Q", scale=alt.Scale(reverse=True)),
    )
)

alt.vconcat(up, middle, down, spacing=0)#.resolve_scale(x="shared")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.