hugovdberg
hugovdberg

Reputation: 1631

How can I position text relative to axes in altair?

I'm trying to make a graph much like the Multi-Line Tooltip Example. However I want to make two modifications. First of all, I want to be able to zoom in to a portion of the data. I fixed that using alt.selection(type="interval", encodings=["x"], bind="scales") and a transform_filter. So far no problem. The problem is that the text labels near the points are overlapping because the lines are close together. Therefore I would like to move the labels to a fixed position within the axes along the top. Is it possible to put the labels at a fixed position within the axes, even when zooming in on the graph (see mockups below)? The problem is that when you zoom in both the x and the y domains change, so the positions of the labels should be expressed as a fraction of the domains.

Another solution I could accept is when the selected value is appended to the legend labels, or some other label outside the plot area.

Mock up of the full view: Full view

Mock up of the zoomed view: Zoomed view

Upvotes: 0

Views: 2663

Answers (1)

jakevdp
jakevdp

Reputation: 86328

You can control the text position with the x and y encodings. Here is an example of placing text at the top of the axis:

import altair as alt
import pandas as pd
import numpy as np

data = pd.DataFrame({
    'x': np.arange(1, 21),
    'y': np.random.randint(0, 20, 20),
})

points = alt.Chart(data).mark_point().encode(
    x='x',
    y='y'
)

text = points.mark_text(baseline='top').encode(
    y=alt.value(0),  # pixels from top
    text='y'
)

points + text

enter image description here

Upvotes: 2

Related Questions