Q: Python Altair plot two standards of deviation Is there a way to make a Python Altair plot showing two standards of deviation? Using mark_errorbar(extent='stdev') shows just one standard deviation.
# Only shows one standard deviation.
alt.Chart(data).mark_errorbar(extent='stdev').encode(
        x=alt.X('quantity:O', title='Quantity'),
        y=alt.Y('value:Q', title='Value')
    )



A: There isn't a parameter values that allows you to do this with mark_errorbar, but you could pre-calculate it in pandas and use mark_rule with y + y2:
import altair as alt
from vega_datasets import data

source = data.cars()

hp_agg = (
    source
    .groupby('Origin')
    ['Horsepower']
    .agg(['mean', 'std'])
    .assign(error_lower = lambda df: df['mean'] - 2 * df['std'],
            error_upper = lambda df: df['mean'] + 2 * df['std'])
    .reset_index())

error_bars = alt.Chart(hp_agg).mark_rule().encode(
    x='Origin',
    y='error_lower',
    y2='error_upper')

means = alt.Chart(hp_agg).mark_circle(color='black').encode(
    x='Origin',
    y='mean')

error_bars + means



You can also achieve the same result using the transforms in Altair instead of using pandas.
import altair as alt
from vega_datasets import data

source = data.cars()

error_bars = (
    alt.Chart(source).mark_rule().encode(
        x='Origin',
        y='error_lower:Q',
        y2='error_upper:Q')    
    .transform_aggregate(
        mean = 'mean(Horsepower)',
        stdev = 'stdev(Horsepower)',
        groupby=['Origin'])
    .transform_calculate(
        error_lower = 'datum.mean - 2 * datum.stdev',
        error_upper = 'datum.mean + 2 * datum.stdev'))
        
means = alt.Chart(source).mark_circle(color='black').encode(
        x='Origin',
        y='mean(Horsepower)')

error_bars + means


