Reputation: 51
How do you create a sortable bar chart in Altair 5 (i.e., sortable alphabetically by category, ascending by value, and descending by value) similar to this one in the D3 gallery?
When I use the following code:
import pandas as pd
import altair as alt
# Sample Data
data = pd.DataFrame({
"Category": ["A", "B", "C", "D", "E"],
"Value": [30, 10, 50, 20, 40]
})
# Create a selection parameter with a dropdown menu for sorting
sort_by = alt.param(
name="sort_by",
bind=alt.binding_select(
options=["Alphabetical", "Ascending", "Descending"],
name="Sort by: "
),
value="Alphabetical" # Default value
)
# Define the sorting field using alt.when
sorting = alt.when(
sort_by == "Alphabetical", "Category",
alt.when(sort_by == "Ascending", "Value", "-Value") # Descending as default
)
# Create the bar chart with dynamic sorting
chart = alt.Chart(data).mark_bar().encode(
x=alt.X("Category:N", sort=sorting, title="Category"),
y=alt.Y("Value:Q", title="Value"),
color=alt.Color("Category:N", legend=None)
).add_params(sort_by).properties(width=500, height=400)
chart
I receive the following error message:
TypeError: Predicate composition is not permitted for 'str'.
Try wrapping 'Value' in a `Parameter` first.
Colab notebook: https://colab.research.google.com/drive/17OoguaVCKIKnGqTfIB-5tb2SfNDJgyjV?usp=sharing
Upvotes: 2
Views: 23