[英]Create Altair chart with grouped dates by week in X axis
DATE,AMOUNT
2022-04-05,100
2022-04-06,10
2022-04-07,90
2022-04-08,75
2022-04-12,32
2022-04-13,400
2022-04-14,28
2022-04-15,50
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
?使用这样的数据集,我如何创建按周分组的条形图,以便 X 轴仅显示两个条形图,
april 03 - april 09
和april 11 - april 17
? (Taking into account that the week starts on sundays, even tho there is no data for dates like april 04
) (考虑到一周从星期日开始,即使没有像
april 04
日这样的日期的数据)
You can use the time units in VegaLite to group observations.您可以使用VegaLite 中的时间单位对观察结果进行分组。
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. week()
将返回周数,但我不确定是否有一种方法可以按照您想要的方式格式化 label,而无需通过labelExpr
手动执行,如下所示。
import pandas as pd
import altair as alt
df = pd.read_clipboard(sep=',')
alt.Chart(df).mark_bar().encode(
x='AMOUNT',
y=alt.Y(
'week(DATE):O', axis=alt.Axis(
labelExpr="datum.label == 'W14' ? 'Apr 04 - Apr 10' : 'Apr 11 - Apr 17'")
)
)
You could also compute the labels via pandas first, which is more automatic than the above:您也可以先通过 pandas 计算标签,这比上面的更自动:
df['DATE'] = pd.to_datetime(df['DATE'])
df_by_week = df.resample('W', on ='DATE').sum().reset_index()
df_by_week['date_label'] = df_by_week['DATE'].apply(
lambda x: f'{(x - pd.Timedelta(days=6)).strftime("%b %d")} - {x.strftime("%B %d")}'
)
alt.Chart(df_by_week).mark_bar().encode(
x='AMOUNT',
y='date_label'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.