简体   繁体   English

带有日期的双轴线的 altair 条形图

[英]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.我按照官方文档创建了一个条形图以及一个独立轴上的折线图,X 轴上是日期。

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: Output:

双轴图表

I tried adjusting the width but the last x-axis label (Fri 19 in above case) still gets cut-off.我尝试调整宽度,但最后一个 x 轴 label(在上述情况下为星期五 19)仍然被切断。 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).同样如您所见,即使 dataframe 没有此类值(没有周末数据),图表中也绘制了两个日期(周六 13 日和周日 14 日)。 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) .您的示例代码实际上为我显示了 Fri 19th,但您可以更明确地设置域并通过scale=alt.Scale(domain=['2021-11-08', '2021-11-20'])))或使用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)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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