Alina V
Alina V

Reputation: 119

Agregate functions block plot interactivity in Altair

Consider the following code adapted from: Altair website

import altair as alt
import pandas as pd

source = pd.DataFrame({
    'a': ['A', 'B', 'B', 'B', 'E', 'F', 'G', 'H', 'I'],
    'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})

alt.Chart(source).mark_bar().encode(
    x='a',
    y='b:Q'
).interactive()

Outputs this plot:

enter image description here

Which is interactive (we can zoom in). However, if I change the Y encoding field to the following (which is what I need) - by adding an Aggregative function:

import altair as alt
import pandas as pd

source = pd.DataFrame({
    'a': ['A', 'B', 'B', 'B', 'E', 'F', 'G', 'H', 'I'],
    'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})

alt.Chart(source).mark_bar().encode(
    x='a',
    y='sum(b):Q'
).interactive()

The plot is no longer interactive. Is it possible to make it interactive while using an Aggregative Function, ie: move it around, zoom in, zoom out?

Thank you :)

Upvotes: 2

Views: 89

Answers (1)

jakevdp
jakevdp

Reputation: 86443

This is a known limitation in Vega/Vega-Lite; see https://github.com/vega/vega-lite/issues/5308

As a workaround, you can pass pre-aggregated data to the chart:

import altair as alt
import pandas as pd

source = pd.DataFrame({
    'a': ['A', 'B', 'B', 'B', 'E', 'F', 'G', 'H', 'I'],
    'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})

data = source.groupby('a').sum().reset_index()

alt.Chart(data).mark_bar().encode(
    x='a',
    y=alt.Y('b', title='Sum of b')
).interactive()

Upvotes: 1

Related Questions