【问题标题】:Fix scale botttom colour on 0 in altair修复 altair 中刻度底部颜色为 0
【发布时间】:2021-07-10 15:51:37
【问题描述】:

我正在通过以下方式生成华夫饼图(类似 github 的活动热图):

import altair as alt
import pandas as pd

# Import data
df = pd.read_csv("https://pastebin.com/raw/AzwJ0va4")

# Year interactive dropdown
years = list(df["year"].unique())
year_dropdown = alt.binding_select(options=years)
selection = alt.selection_single(
    fields=["year"], bind=year_dropdown, name="Year", init={"year": 2020}
)

# Plot
(
    alt.Chart(df)
    .mark_rect()
    .encode(
        x=alt.X("week:O", title="Week"),
        y=alt.Y("day(committed_on):O", title=""),
        color=alt.Color(
            "hash:Q", scale=alt.Scale(range=["transparent", "green"]), title="Commits"
        ),
        tooltip=[
            alt.Tooltip("committed_on", title="Date"),
            alt.Tooltip("day(committed_on)", title="Day"),
            alt.Tooltip("hash", title="Commits"),
        ],
    )
    .add_selection(selection)
    .transform_filter(selection)
    .properties(width=1000, height=200)
)

结果图的行为符合我的预期,达到 99%,但是当我选择没有活动的年份(hash 列填充为 0)作为 2017 时,该图将填充0 的绿色方块正好锚定在刻度的中间。

如何确保 0 始终位于刻度的底部? (透明色)

【问题讨论】:

    标签: python pandas altair vega


    【解决方案1】:

    您可以设置色标的domain,就像为轴设置它一样:scale=alt.Scale(range=["transparent", "green"], domain=[0, 16])。可以在较新版本的 VegaLite 中仅设置 domainMin,但在 Altair 中尚未设置。在您的情况下,无论如何设置 min 和 max 可能是一个好主意,以便所有年份的颜色都被解释为相同。

    【讨论】:

    • 我认为这绝对是朝着正确方向迈出的一步,但我希望在domain 中有一个更高的界限,它会随着选择器动态更新。对于给定的年份,每天 100 次提交可能很多,而在另一年则不会(因此大多数年份将大多接近白色且难以阅读)。不知道是否有办法访问selection 值并在每次渲染绘图时动态找到最大值。无论如何,感谢您记下回复
    • @anddt 我认为在 Altair 更新为包含用于刻度的 domainMin 参数之前这是不可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2021-12-15
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多