Altair 区域图不显示

1 投票
1 回答
27 浏览
提问于 2025-04-14 15:29

我正在尝试从一些Kaggle的数据中创建一个分区域图:https://www.kaggle.com/datasets/jessemostipak/hotel-booking-demand,但是有些地方出问题了。

import pandas as pd
import altair as alt
from vega_datasets import data

# Load the hotel bookings dataset
df = pd.read_csv('hotel_bookings.csv')

# Sum the columns adults, children, and babies to get the total number of guests
df['total_guests'] = df['adults'] + df['children'] + df['babies']

# Group by country and sum the total number of guests
guests_by_country = df.groupby('country')['total_guests'].sum().reset_index()

# Load the world map data
world_map_data = alt.topo_feature(data.world_110m.url, 'countries')

# Create the Altair chart
chart = alt.Chart(world_map_data).mark_geoshape().encode(
    color=alt.Color('total_guests:Q', scale=alt.Scale(scheme='plasma')),
    tooltip=['country:N', 'total_guests:Q']
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(data=guests_by_country, key='country', fields=['total_guests'])
).project(
    type='naturalEarth1'
).properties(
    title='Country Wise Distribution of Guests'
).configure_view(
    stroke='black'
).configure_title(
    fontSize=20
)

# Show the chart
chart


这是输出的结果:

在这里输入图片描述

1 个回答

0

我觉得问题的原因是,topojson里的id和用户数据中的国家名称不匹配。我找不到最合适的topojson数据,所以我从countries-110m.json下载了一个包含国家名称的世界地图的topojson数据。然后我又下载了ISO3的数据,并把它合并到最终的数据框中,这样就能把topojson和国家名称关联起来了。

import pandas as pd
import altair as alt
from vega_datasets import data

# Load the hotel bookings dataset
df = pd.read_csv('./data/hotel_bookings.csv')

# Sum the columns adults, children, and babies to get the total number of guests
df['total_guests'] = df['adults'] + df['children'] + df['babies']

# Group by country and sum the total number of guests
guests_by_country = df.groupby('country')['total_guests'].sum().reset_index()

# read iso3
iso3 = pd.read_csv('./data/iso3.csv')

# merge
source = pd.merge(guests_by_country, iso3, left_on='country', right_on='iso3').drop(columns='iso3')

# Load the world map data
url = 'https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json'
world_map_data = alt.topo_feature(url, 'countries')

# Create the Altair chart
chart = alt.Chart(world_map_data).mark_geoshape().encode(
    color=alt.Color('total_guests:Q', scale=alt.Scale(scheme='plasma')),
    tooltip=['country:N', 'total_guests:Q']
).transform_lookup(
    lookup='properties.name',
    from_=alt.LookupData(data=source, key='name', fields=['country','total_guests'])
).project(
    type='naturalEarth1'
).properties(
    title='Country Wise Distribution of Guests',
    width=600,
    height=400,
).configure_view(
    stroke='black'
).configure_title(
    fontSize=20
)

# Show the chart
chart

enter image description here

撰写回答