Open joelostblom opened 7 months ago
It is possible to control bin extents using selections, but I need to play with it to figure it out again.
I think you can do alt.Bin(maxbins=20, extent=interval_selection)
, where interval_selection
is bound to the axes.
While I couldn't find a way to bind the maxbins value to the slider, another approach is to bind the slider to an opacity value. This approach leaves the domain of the color scale static, which is a big shortcoming. As the bin size changes, the color scale should be adjusted. Any suggestions?
import altair as alt
from vega_datasets import data
source = data.movies.url
layer_60 = alt.Chart(source).mark_rect().encode(
x=alt.X('IMDB_Rating:Q', bin=alt.Bin(maxbins=60)),
y=alt.Y('Rotten_Tomatoes_Rating:Q', bin=alt.Bin(maxbins=60)),
color=alt.Color('count():Q', scale=alt.Scale(scheme='greenblue')),
opacity=alt.condition(
"binSize.binSize == 60",
alt.value(1),
alt.value(0)
),
tooltip=['count()', 'IMDB_Rating:Q', 'Rotten_Tomatoes_Rating:Q']
)
layer_120 = alt.Chart(source).mark_rect().encode(
x=alt.X('IMDB_Rating:Q', bin=alt.Bin(maxbins=120)),
y=alt.Y('Rotten_Tomatoes_Rating:Q', bin=alt.Bin(maxbins=120)),
color=alt.Color('count():Q', scale=alt.Scale(scheme='greenblue')),
opacity=alt.condition(
"binSize.binSize == 120",
alt.value(1),
alt.value(0)
),
tooltip=['count()', 'IMDB_Rating:Q', 'Rotten_Tomatoes_Rating:Q']
)
layer_180 = alt.Chart(source).mark_rect().encode(
x=alt.X('IMDB_Rating:Q', bin=alt.Bin(maxbins=180), title=''),
y=alt.Y('Rotten_Tomatoes_Rating:Q', bin=alt.Bin(maxbins=180), title=''),
color=alt.Color('count():Q', scale=alt.Scale(scheme='greenblue')),
opacity=alt.condition(
"binSize.binSize == 180",
alt.value(1),
alt.value(0)
),
tooltip=['count()', 'IMDB_Rating:Q', 'Rotten_Tomatoes_Rating:Q']
)
# Combine all layers
combined_chart = alt.layer(
layer_60, layer_120, layer_180
).properties(
width=400,
height=300,
)
# Add slider for bin size selection
bin_slider = alt.binding_range(min=60, max=180, step=60, name='Bin Size')
bin_select = alt.selection_point(name="binSize", fields=['binSize'], bind=bin_slider, value=120)
# Final chart with selection
chart = alt.layer(combined_chart).add_params(bin_select)
chart
I saw this cool example from @dwootton and think it could be cool to have in the altair example gallery (it's even cooler when the adjusting is bound to zooming the chart, but my understanding is that this is not possible in VL directly)
Open the Chart in the Vega Editor