JavaScript
x
10
10
1
DATE,AMOUNT
2
2022-04-05,100
3
2022-04-06,10
4
2022-04-07,90
5
2022-04-08,75
6
2022-04-12,32
7
2022-04-13,400
8
2022-04-14,28
9
2022-04-15,50
10
With a dataset like this, how can I create a bar chart grouped by week so the X axis shows only two bars, april 03 - april 09
and april 11 - april 17
? (Taking into account that the week starts on sundays, even tho there is no data for dates like april 04
)
Advertisement
Answer
You can use the time units in VegaLite to group observations. week()
will return the week number, but I am not sure there is a way to format the label the way you want without doing it manually via labelExpr
as I have done below.
JavaScript
1
13
13
1
import pandas as pd
2
import altair as alt
3
4
df = pd.read_clipboard(sep=',')
5
6
alt.Chart(df).mark_bar().encode(
7
x='AMOUNT',
8
y=alt.Y(
9
'week(DATE):O', axis=alt.Axis(
10
labelExpr="datum.label == 'W14' ? 'Apr 04 - Apr 10' : 'Apr 11 - Apr 17'")
11
)
12
)
13
You could also compute the labels via pandas first, which is more automatic than the above:
JavaScript
1
10
10
1
df['DATE'] = pd.to_datetime(df['DATE'])
2
df_by_week = df.resample('W', on ='DATE').sum().reset_index()
3
df_by_week['date_label'] = df_by_week['DATE'].apply(
4
lambda x: f'{(x - pd.Timedelta(days=6)).strftime("%b %d")} - {x.strftime("%B %d")}'
5
)
6
alt.Chart(df_by_week).mark_bar().encode(
7
x='AMOUNT',
8
y='date_label'
9
)
10