Ray
Ray

Reputation: 8573

Python Altair, pin text to bottom-right of chart

How do I pin a piece of text, for example with mark_text(), to the bottom-right of the chart, so that it stays at the bottom-right corner of the chart, even when the chart is resized with, say, .properties()? I know I can do the following:

chart = altair.Chart().mark_text(text="WTF!?!?", align="right", baseline="bottom").properties(width=300, height=100)
chart = chart.encode(x=altair.value(chart.width), y=altair.value(chart.height))

But with the above, the text doesn't stay at the bottom-right corner, for example if I do chart.properties(width=500, height=500). Is there a way of doing this that is robust to resizing?

The reason I want to do this is that I have one piece of code that plots a bunch of charts, and another separate function that decides the size and layouts of the charts based on how many there are and what available space there is on the screen. There are pieces of text in each chart that need to stay at the bottom-right corner of the chart, whatever resizing is applied to the chart.

Upvotes: 1

Views: 689

Answers (1)

joelostblom
joelostblom

Reputation: 48929

alt.value anchors elements to a pixel value, whereas alt.datum anchors elements to a value on the scale's domain (which means it stays in place as the pixel width/height of the chart changes):

import altair as alt
import pandas as pd

points = alt.Chart(pd.DataFrame({'x': [0, 1], 'y': [2, 3]})).mark_point().encode(x='x', y='y')
text = chart.mark_text(text="WTF!?!?", dx=-20, dy=-5).encode(x=alt.datum(1), y=alt.datum(0))
points + text

enter image description here

(points + text).properties(width=700, height=50)

enter image description here

Upvotes: 2

Related Questions