johnsinclair
johnsinclair

Reputation: 109

How to show a vertical line in an Altair chart using mark_rule()

I am creating an histogram using Python & Altair. I am able to include a vertical line as the mean, which works, but the code for the first Quartile (25th quantile) does not produce a vertical line.

I assume it is based that I use a numpy function to calculate the first quartile. But I am unsure how to do it differently.

What am I missing? Thank you!

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

df = pd.util.testing.makeDataFrame()

chart = (
    alt.Chart(df)
    .mark_bar()
    .encode(alt.X("A:Q", bin = True), y = "count()")
    .properties(width = 800, height = 300)
) 

# create mean rule ***WORKS***
mean = (
    alt.Chart(df)
    .mark_rule()
    .encode(
        x = "mean(A):Q"
    )
)

chart + mean

enter image description here

# create Q1 rule *** vertical line is NOT showing***
Q1 = (
    alt.Chart(df)
    .mark_rule()
    .encode(
        x = "np.quantile(A, 0.25):Q"
    )
)

chart + Q1

enter image description here

Any suggestions? Thank you!

Upvotes: 1

Views: 6144

Answers (1)

jakevdp
jakevdp

Reputation: 86320

Altair encoding strings do not parse arbitrary python code, so calling numpy functions will not work.

For quantiles in Altair, you can use the quantile transform. Here is an example with your data:

Q1 = (
    alt.Chart(df)
    .transform_quantile('A', probs=[0.25], as_=['prob', 'value'])
    .mark_rule()
    .encode(
        x = "value:Q"
    )
)

chart + Q1

enter image description here

Upvotes: 3

Related Questions