【问题标题】:Altair mark_text labels where domain in x-axis is linkedAltair mark_text 标签,其中 x 轴中的域被链接
【发布时间】:2021-02-03 05:08:12
【问题描述】:

我试图在某个 altair 图表上提供文本标签,该图表链接到另一个图表中的选定间隔。我意识到“mark_text ()”给出的文本没有完全显示在图表的最后一点,其中 x 轴中的域被指定为选定的间隔,我也不知道如何指定格式,因此日期将被指定为 yyyy-mm 或月-年(不想显示日期)。

我意识到的另一件事是,当图形的 x 轴上的域也链接到另一个图表中选择的区间时,工具提示根本不显示 ,这就是我使用 mark_text()
的原因 我正在使用的代码如下

import altair as alt
from vega_datasets import data

nearest = alt.selection_single(nearest=True, on='mouseover',
                    encodings=['x','y'], empty='none')
interval = alt.selection_interval(encodings=['x'])
weather = data.seattle_weather()
base = alt.Chart(weather).mark_rule(size=2).encode(
x='date:T')

chart = base.mark_line().encode(
x=alt.X('date:T', scale=alt.Scale(domain=interval.ref())),
    y='temp_max:Q',).properties(
width=800,
height=300)

text=base.mark_text(align='left', dx=5, dy=5).encode(
y='temp_max:Q',
text=alt.condition(nearest, 'label:N', alt.value(' '))
).transform_calculate(label='"Date: " + format(datum.date, "") '
                     ).properties(selection=nearest,width=800,
height=300)

point=base.mark_point().encode(y='temp_max:Q',opacity=alt.condition(nearest, alt.value(1), alt.value(0)))



view = base.mark_line().add_selection(
interval).properties(width=800, height=20)


(point+text+chart) &view

【问题讨论】:

    标签: python charts altair vega-lite


    【解决方案1】:

    您似乎正在尝试使用图层创建工具提示,这就是您遇到许多问题的原因。您是否考虑过使用工具提示编码?

    import altair as alt
    from vega_datasets import data
    
    nearest = alt.selection_single(nearest=True, on='mouseover',
                        encodings=['x','y'], empty='none')
    interval = alt.selection_interval(encodings=['x'])
    weather = data.seattle_weather()
    
    line = alt.Chart(weather).mark_line().encode(
        x=alt.X('date:T', scale=alt.Scale(domain=interval)),
        y='temp_max:Q'
    ).properties(
        width=800,
        height=200
    )
    point = line.mark_point().encode(
        tooltip='yearmonth(date):N',
        opacity=alt.condition(nearest, alt.value(1), alt.value(0))
    ).add_selection(nearest)
    
    view = alt.Chart(weather).mark_line().encode(
        x='date:T',
    ).properties(
        width=800,
        height=20
    ).add_selection(interval)
    
    (point + line) & view
    

    【讨论】:

    • 非常感谢,我第一次尝试使用工具提示编码,但不知何故,当 x 轴被间隔选择修改时它不起作用,所以这就是为什么我决定用一个 mark_text 层,你肯定是个魔术师 :) 再次感谢你。
    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多