Altair绘制Pandas汇率热力图时矩形宽度异常问题排查
汇率热力图显示异常的修复方案
问题背景
我有一个存储每日汇率的Pandas DataFrame,数据样例如下:
print(df[['Date', 'Currency', 'Rate']].head())
输出结果:
Date Currency Rate 18 2023-12-01 AUD 1.64655 19 2023-12-01 BRL 5.36325 13 2023-12-01 CAD 1.47360 20 2023-12-01 CHF 0.95290 6 2023-12-01 CNY 7.78240
希望绘制热力图,使每个日期-货币组合对应一个彩色矩形,但通过Streamlit+Altair实现的代码运行后,每个货币仅显示一个矩形(使用mark_circles()时显示正常)。当前代码如下:
def generate_heatmap(df): # Adding a bit more information on the color scale for debugging df = df.sort_values(by=['Date', 'Currency']) scale = alt.Scale(scheme='viridis', domain=[df['Rate'].min(), df['Rate'].max()]) print(df[['Date', 'Currency', 'Rate']].head()) heatmap = alt.Chart(df).mark_rect().encode( x=alt.Y('Date:T', axis=alt.Axis(title='Date', format='%Y-%m-%d')), y='Currency:N', color=alt.Color('Rate:Q', scale=scale, legend=alt.Legend(title="Exchange Rate")) ).configure_scale( bandPaddingInner=0.1 ) return heatmap chart = generate_heatmap(df_chart) st.altair_chart(chart, use_container_width=True)
修复方案
核心问题定位
问题出在x轴的编码错误:你误将alt.X写成了alt.Y,导致日期被映射到y轴,与Currency字段重叠,最终每个货币仅显示一个矩形。此外,为了保证每个日期对应的矩形宽度一致,建议将日期转为离散类别类型。
修改后的完整代码
def generate_heatmap(df): df = df.sort_values(by=['Date', 'Currency']) scale = alt.Scale(scheme='viridis', domain=[df['Rate'].min(), df['Rate'].max()]) heatmap = alt.Chart(df).mark_rect().encode( # 修正1:将alt.Y改为alt.X,同时指定日期为离散类型(O) x=alt.X('Date:O', axis=alt.Axis(title='Date', format='%Y-%m-%d', labelAngle=-45)), y=alt.Y('Currency:N', axis=alt.Axis(title='Currency')), color=alt.Color('Rate:Q', scale=scale, legend=alt.Legend(title="Exchange Rate")) ).configure_scale( bandPaddingInner=0.1 ) return heatmap chart = generate_heatmap(df_chart) st.altair_chart(chart, use_container_width=True)
关键修改说明
- 修正x轴编码:将
alt.Y('Date:T')改为alt.X('Date:O'),让日期正确映射到x轴,同时Date:O将日期作为离散类别处理,避免连续时间轴导致的矩形宽度不均问题。 - 添加
labelAngle=-45:旋转日期标签,避免标签重叠,提升图表可读性。
内容的提问来源于stack exchange,提问作者Jiří Procházka
相关产品推荐
相关产品推荐

