Search code examples
altair

Altair: rotate shapes in scatterplot


Using this as an example (my plot is actually a bit more complicated, therefore this example):

import altair as alt
from vega_datasets import data

    source = data.stocks()

    x = alt.Chart(source).mark_point().encode(
        x='date',
        y='price',
        color='symbol',
        shape=alt.Shape('symbol', scale=alt.Scale(range=['cross', 'circle', 'square', 'triangle-right', 'diamond']))
    )

How can I use alt.Scale(range=['cross', ...]) and rotate some (for instance only the cross) of my symbols?

Thank you!


Solution

  • Try using the angle=alt.Angle() encoding channel. For example:

    import altair as alt
    from vega_datasets import data
    
    source = data.stocks()
    source['angle'] = 'angle-cat-one'
    source.loc[source.symbol == 'GOOG', 'angle'] = 'angle-cat-two'
    
    x = alt.Chart(source).mark_point().encode(
        x='date',
        y='price',
        color='symbol',
        shape=alt.Shape('symbol', scale=alt.Scale(range=['cross', 'circle', 'square', 'triangle-right', 'diamond'])),
        angle=alt.Angle('angle:N', scale=alt.Scale(domain=['angle-cat-one', 'angle-cat-two'], range=[0, 45]))
    )
    x
    

    enter image description here

    Here the square-symbol is rotated in the chart based on the added angle column in the dataframe. I map the category values to a rotation value in degree using the a domain-range mapping in the scale of the angle encoding.

    I noticed that this approach does not reflect the rotation in the legend.