![](/img/trans.png)
[英]How to add a series specific line y=x to a faceted (or similar) dual-axis chart in Altair?
[英]altair bar chart with Line on Dual Axis with dates
我按照官方文檔創建了一個條形圖以及一個獨立軸上的折線圖,X 軸上是日期。
這是代碼片段
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:
我嘗試調整寬度,但最后一個 x 軸 label(在上述情況下為星期五 19)仍然被切斷。 有什么技巧可以避免這種情況嗎?
同樣如您所見,即使 dataframe 沒有此類值(沒有周末數據),圖表中也繪制了兩個日期(周六 13 日和周日 14 日)。 這在圖表中造成了很大的差距,尤其是當幾個月有更多行時。 如何防止這些日期出現在圖表中?
您的示例代碼實際上為我顯示了 Fri 19th,但您可以更明確地設置域並通過scale=alt.Scale(domain=['2021-11-08', '2021-11-20'])))
或使用scale=alt.Scale(nice=True)
。
我不確定您是否可以在時間軸上存在間隙,因為它們本質上是連續的。 聽起來序數軸可能更適合您?
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.