How to add error bars to alt.Chart with binned x-values

Viewed 66

I can create a simple bar chart with the code below, but I want to add error bars if that is even possible.

gm12878_close_TAD_df = pd.DataFrame(gm12878_close, columns=['distance'])
gm12878_close_TAD_df_500kb = gm12878_close_TAD_df[gm12878_close_TAD_df['distance'] < 10000]

alt.Chart(gm12878_close_TAD_df_500kb).mark_bar().encode(x = alt.X('distance', bin=alt.Bin(maxbins=30)), y='count()')

Which produces this chart: CHART PRODUCED HERE

To add error bars I have been trying to use something like this based off this link (https://altair-viz.github.io/gallery/grouped_bar_chart_with_error_bars.html)

chart = alt.Chart(gm12878_close_TAD_df_500kb).mark_bar().encode(x = alt.X('distance', bin=alt.Bin(maxbins=30)), y='count()')
error_bars = chart.mark_errorbar(extent='ci').encode(x = 'distance', y='count():Q')
    
    
alt.layer(chart, error_bars)

I would appreciate any suggestions and help. Thank you in advanced.

1 Answers

You cannot create an error bar from a count because it is a single number; an error bar needs multiple values within the same group to derive a measure of uncertainty such as a confidence interval. You would also need to bin the x-axis for the error bar, so that it corresponds to the axis of the other layered chart. Here is an example

import altair as alt
from vega_datasets import data

source = data.movies.url

mean_points = alt.Chart(source).mark_circle(color='black').encode(
    alt.X("IMDB_Rating:Q", bin=True),
    y='mean(Worldwide_Gross):Q',
)

error_bars = alt.Chart(source).mark_errorbar(extent='ci').encode(
    alt.X("IMDB_Rating:Q", bin=True),
    y='Worldwide_Gross:Q',
)

mean_points + error_bars

enter image description here

Related