Reputation: 109
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
# create Q1 rule *** vertical line is NOT showing***
Q1 = (
alt.Chart(df)
.mark_rule()
.encode(
x = "np.quantile(A, 0.25):Q"
)
)
chart + Q1
Any suggestions? Thank you!
Upvotes: 1
Views: 6144
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
Upvotes: 3