Reputation: 103
I'm trying to do something like below.
Group by the date column, for example year or year/month. And visualize a stacked bar chart, based on the True/False value.
What's the best way to go about this in Altair?
df = pd.DataFrame({
'date': ['20-03-2017', '20-03-2017', '20-03-2018', '21-03-2018', '20-10-2019', '20-03-2019', '1-02-2019', '10-03-2020', '20-06-2020'],
'value': [True, True, True, False, True, False, False, True, False]
})
import altair as alt
alt.Chart(df).mark_bar().encode(
x = 'groupbyyear(date)',
y = 'count(value)',
color = 'value'
)
Upvotes: 1
Views: 718
Reputation: 86433
You're very close: instead of groupbyyear
you can use a year
time unit transform, and since your dates are non-standard format, you can first use pandas to_datetime
to convert them to standard date values. The result looks like this:
import altair as alt
import pandas as pd
df = pd.DataFrame({
'date': ['20-03-2017', '20-03-2017', '20-03-2018', '21-03-2018', '20-10-2019', '20-03-2019', '1-02-2019', '10-03-2020', '20-06-2020'],
'value': [True, True, True, False, True, False, False, True, False]
})
df['date'] = pd.to_datetime(df['date'])
alt.Chart(df).mark_bar().encode(
x = 'year(date):O',
y = 'count(value)',
color = 'value'
)
Upvotes: 1