将条形图上的颜色与牵牛星一起使用,似乎可以防止标度上的零=假产生预期效果

2024-06-02 08:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

下面代码中的第一个图表(基于此:https://altair-viz.github.io/gallery/us_population_over_time_facet.html)似乎强制Y轴不从零开始,正如预期的那样。但是第二个图表,在编码中包含了一种颜色,似乎使alt.Scale中的0=False不再受到重视

编辑:忘记提到使用Altair 4.1.0

import altair as alt
from vega_datasets import data
import pandas as pd

source = data.population.url

df = pd.read_json(source)
df = df[df["age"] <= 40]

alt.Chart(df).mark_bar().encode(
    x="age:O",
    y=alt.Y(
        "sum(people):Q",
        title="Population",
        axis=alt.Axis(format="~s"),
        scale=alt.Scale(zero=False),
    ),
    facet=alt.Facet("year:O", columns=5),
).resolve_scale(y="independent").properties(
    title="US Age Distribution By Year", width=90, height=80
)

alt.Chart(df).mark_bar().encode(
    x="age:O",
    y=alt.Y(
        "sum(people):Q",
        title="Population",
        axis=alt.Axis(format="~s"),
        scale=alt.Scale(zero=False),
    ),
    facet=alt.Facet("year:O", columns=5),
    color=alt.Color("year"),
).resolve_scale(y="independent").properties(
    title="US Age Distribution By Year", width=90, height=80
)

enter image description here

enter image description here


Tags: importfalsedfagedatatitleas图表
1条回答
网友
1楼 · 发布于 2024-06-02 08:21:12

这是因为比例会自动调整,以显示要着色的变量中的所有组。如果我们查看具有堆叠颜色的单个条形图,则更容易理解:

import altair as alt
from vega_datasets import data
import pandas as pd

source = data.population.url

df = pd.read_json(source)
df = df[df["age"] <= 40]

alt.Chart(df.query('year < 1880')).mark_bar().encode(
    x="age:O",
    y=alt.Y(
        "sum(people):Q",
        axis=alt.Axis(format="~s"),
        scale=alt.Scale(zero=False)),
    color=alt.Color("year"))

enter image description here

你在计算总和,这意味着所有的年份都会在酒吧里的某个地方,彼此叠加在一起。Altair/Vega Lite会扩展轴,以便包含彩色变量中的所有组

如果改为按年龄着色,则轴将再次扩展以包括所有着色组,但由于它们现在不在每个条的底部,因此轴将被剪切到零以上

import altair as alt
from vega_datasets import data
import pandas as pd

source = data.population.url

df = pd.read_json(source)
df = df[df["age"] <= 40]

alt.Chart(df.query('year < 1880')).mark_bar().encode(
    x="age:O",
    y=alt.Y(
        "sum(people):Q",
        axis=alt.Axis(format="~s"),
        scale=alt.Scale(zero=False)),
    color=alt.Color("age"))

enter image description here

唯一的差异是为什么它不在第一个绘图中显示最暗颜色的尖端,然后切割大约2米?我不太清楚这件事

相关问题 更多 >