You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Altair 4.2.2调用alt.x等属性出现AttributeError问题求助

AttributeError: module 'altair' has no attribute 'x'(Altair 4.2.2版本)

问题场景

我正在学习Python的Altair可视化教程,已成功加载并处理数据:

df = pd.read_csv("https://raw.githubusercontent.com/onlyphantom/miband/main/data/run_1km.csv", parse_dates=['startTime'])
df['day_of_week'] = df['startTime'].dt.day_name()
df.head()

使用简单编码方式生成了散点图:

alt.Chart(df).mark_point().encode(
x = "seconds_per_km",
y = "day_of_week",
color ="day_of_week"
).interactive()

但改用如下代码时出现错误:

alt.Chart(df).mark_point().encode(
    alt.x("seconds_per_km"),
    alt.y("day_of_week"),
    alt.color("day_of_week")
).interactive()

错误信息为:

AttributeError: module 'altair' has no attribute 'x'

使用的是Altair 4.2.2版本,请问该错误原因是什么?

解答

在Altair 4.x版本中,alt.x、alt.y这类小写的顶层编码属性不存在,这类显式编码对象需要通过首字母大写的类来调用(比如alt.X、alt.Y、alt.Color)。

修正后的代码如下:

alt.Chart(df).mark_point().encode(
    alt.X("seconds_per_km"),
    alt.Y("day_of_week"),
    alt.Color("day_of_week")
).interactive()

补充说明:alt.x这类小写简化写法是Altair 5.x版本才引入的语法。如果想要使用这种更简洁的写法,需要把Altair升级到5.x及以上版本;若要保持4.2.2版本,则必须使用首字母大写的编码类。

内容的提问来源于stack exchange,提问作者elksie5000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:38:08