简体   繁体   中英

altair bar chart with Line on Dual Axis with dates

I followed the official docs to create a bar chart along with a line chart on independent axis with dates on the X-axis.

Here is the code snippet

df = pd.DataFrame({
    'reportday': ['2021-11-08', '2021-11-09', '2021-11-10', '2021-11-11','2021-11-12', '2021-11-15','2021-11-16', '2021-11-17', '2021-11-18','2021-11-19'],
    'price': [328.0, 310.0, 301.0, 3330.0, 3278.0, 3200.0, 2189.0, 1701.0, 1698.0, 1703.0],
    'production': [24.75, 16.30, 14.77, 14.10, 27.70, 26.70, 29.05, 19.58, 24.88, 17.35]
})
df['reportday'] = pd.to_datetime(df['reportday'])    
base = alt.Chart(df).encode(x=alt.X('reportday:T', axis=alt.Axis(labelAngle=325)))
line =  base.mark_line(color='red').encode(y=alt.Y('price:Q', axis=alt.Axis(grid=True)))
bar = base.mark_bar().encode(y='production:Q')
c = (line + bar).resolve_scale(y='independent').properties(width=600)

Output:

双轴图表

I tried adjusting the width but the last x-axis label (Fri 19 in above case) still gets cut-off. Any tips to avoid this?

Also as you can see, there are two dates (Sat 13 and Sun-14) being plotted in the chart even though the dataframe has no such values (there is no data for weekends). This puts a big gap in the chart especially when there are lot more rows for several months. How do I prevent these dates from showing up in the chart?

You example code actually shows Fri 19th for me, but you can be more explicit and set the domain via scale=alt.Scale(domain=['2021-11-08', '2021-11-20']))) or use scale=alt.Scale(nice=True) .

I am not sure you can have gaps in time axes since they are continuous by nature. It sounds like an ordinal axis might be more suitable for you?

base = alt.Chart(df).encode(x=alt.X('monthdate(reportday):O', axis=alt.Axis(labelAngle=325)))
line =  base.mark_line(color='red').encode(y=alt.Y('price:Q', axis=alt.Axis(grid=True)))
bar = base.mark_bar().encode(y='production:Q')

(bar + line).resolve_scale(y='independent').properties(width=600)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM