如何解决 Altair 中奇怪的绘图错误

问题描述 投票:0回答:1

我正在尝试绘制一些数据,这些数据大致应该形成这样的地图:

import numpy as np
lats = np.random.uniform(51.5, 51.6, 100)
lons = np.random.uniform(-0.1, 0.1, 100)
months = np.arange(1, 13)
vouchers = np.random.randint(1, 100, 100)
test_df = pd.DataFrame({
    'lat': lats,
    'lon': lons,
    'month': np.random.choice(months, 100),
    'vouchers': vouchers
})
test_df 

alt.Chart(test_df).mark_circle().encode(
    longitude='lon:Q',
    latitude='lat:Q',
    size='vouchers:Q',
    color='month:N'
)

看起来像这样:

enter image description here

不管怎样,我的真实数据很相似。

描述显示:

enter image description here

并且数据是正确的数据类型:

enter image description here

这是我的代码:

alt.Chart(lunch_vouchers).mark_circle().encode(
    longitude='long_jittered:Q',
    latitude='lat_jittered:Q',
    size=alt.Size('Total_People_in_voucher:Q', scale=alt.Scale(range=[0, 1000]), legend=None),
    color=alt.value('red'),
    tooltip=['Postcode', 'Total_People_in_voucher', 'Month']
)

但是它在 VSCode 中产生了奇怪的显示错误。

enter image description here

有人可以帮忙吗?

python altair
1个回答
0
投票

如果您在 Altair 中遇到奇怪的绘图错误请尝试以下解决方案:

检查数据类型: 使用 df.dtypes 确保列具有正确的数据类型。如果需要的话用 astype() 修复。

正确使用 .mark_*(): 在创建 Chart 对象后,始终像 mark_line() 一样链接 .mark_*() 。

更新 Altair: 运行 pip install --upgrade altair 以避免旧版本中的错误。

渲染器问题: 使用 alt.renderers.enable('default') 或 'notebook' 手动设置渲染器。

行限制: 使用 alt.data_transformers.disable_max_rows() 禁用 5000 行限制。

检查缺失值:使用 df.isna().sum() 并处理缺失数据。

正确编码:确保.encode()中的列名称与DataFrame完全匹配。

© www.soinside.com 2019 - 2024. All rights reserved.