I would like to rotate text based on a value specified in a column of my pandas DataFrame. It seems the angle parameter of text_config only takes float values and no feature name.

import pandas as pd
import altair as alt

data = pd.DataFrame(
    {
        "x": [0, 1, 0, -1],
        "y": [1, 0, -1, 0],
        "name": ["UP", "RIGHT", "BOTTOM", "LEFT"],
        "angle": {180, 270, 0, 90},
    }
)

alt.Chart(data).encode(x="x", y="y", text="name").mark_text(angle='angle')

1 Answers

1
jakevdp On Best Solutions

Unfortunately, text angle is not available as an encoding channel. The best you can do is to manually split the data and layer marks with the desired angles; for example:

import pandas as pd
import altair as alt

data = pd.DataFrame(
    {
        "x": [0, 1, 0, -1],
        "y": [1, 0, -1, 0],
        "name": ["UP", "RIGHT", "BOTTOM", "LEFT"],
        "angle": [180, 270, 0, 90],
    }
)

base = alt.Chart(data).encode(x="x", y="y", text="name")

layers = [
    base.transform_filter(alt.datum.name == name).mark_text(angle=angle)
    for (name, angle) in zip(data.name, data.angle)
]

alt.layer(*layers)

enter image description here