Search code examples
pythonchartsaltairvega-lite

Altair mark_text labels where domain in x-axis is linked


I was trying to give text labels on some altair chart linked to a selected interval from another chart. I realize that the text given by "mark_text ()" doesn't show completely at the last points of the chart where the domain in the x-axis is specified to be the interval selected, also I didn't know how to specify the format so the dates will be given just as yyyy-mm or month-year (don't want to display the day).

Another thing that I realized, is when one specifies the tooltip doesn't show at all when the domain on the x-axis of the graph is also linked to an interval selected in another chart , that's the reason I used the mark_text()
the code I'm using is the following

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

Solution

  • It looks like you're trying to create a tooltip using a layer, and this is the cause of many of the problems you're having. Have you considered using the tooltip encoding?

    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