将列表列编码为绘图图例

2024-09-29 21:47:19 发布

您现在位置:Python中文网/ 问答频道 /正文

提前道歉,我不知道如何最好地表达这个问题:

我正在处理一个大型数据集,我想绘制纬度和经度,其中点的颜色(实际上是不透明度)编码为绑定到图例的“FeatureType”列。这样,我可以使用图例在地图上突出显示我正在寻找的各种特征

Here is a picture of my map and legend so far

问题在于,在我的数据集中,“FeatureType”列是可以在其中找到的特征列表(即拱门、桥梁等)

我怎样才能做到拱门和桥梁都能看到这一点呢。目前,它创建了自己的类别(拱门、桥梁等),导致约20种不同特征类型的300多个组合

数据集可在http://atlantides.org/downloads/pleiades/dumps/pleiades-locations-latest.csv.gz找到

注:我用的是牵牛星/熊猫

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


df = pd.read_csv ('C://path/pleiades-locations.csv') 

alt.data_transformers.enable('json')

countries = alt.topo_feature(data.world_110m.url, 'countries')

selection = alt.selection_multi(fields=['featureType'], bind='legend')

brush = alt.selection(type='interval', encodings=['x'])

map = alt.Chart(countries).mark_geoshape(
    fill='lightgray',
    stroke='white'
).project('equirectangular').properties(
    width=500,
    height=300
)

points = alt.Chart(df).mark_circle().encode(
    alt.Latitude('reprLat:Q'),
    alt.Longitude('reprLong:Q'),
    alt.Color('featureType:N'),
    tooltip=['featureType','timePeriodsKeys:N'],
    opacity=alt.condition(selection, alt.value(1), alt.value(0.0))
).add_selection(
    selection)

(map + points)

Tags: csv数据importmapdata特征altcountries
1条回答
网友
1楼 · 发布于 2024-09-29 21:47:19

Altair无法从当前列格式生成所需的标签。您需要将逗号分隔的字符串标签转换为列表,然后explode the column,以便列表中的每个项目都有一行:

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

alt.data_transformers.enable('data_server')

df = pd.read_csv('http://atlantides.org/downloads/pleiades/dumps/pleiades-locations-latest.csv.gz')[['reprLong', 'reprLat', 'featureType']]
df['featureType'] = df['featureType'].str.split(',')
df = df.explode('featureType')

countries = alt.topo_feature(data.world_110m.url, 'countries')

world_map = alt.Chart(countries).mark_geoshape(
    fill='lightgray',
    stroke='white')

points = alt.Chart(df).mark_circle(size=10).encode(
    alt.Latitude('reprLat:Q'),
    alt.Longitude('reprLong:Q'),
    alt.Color('featureType:N', legend=alt.Legend(columns=2)))

world_map + points

enter image description here

请注意,图例中有这么多条目是没有意义的,因为颜色是重复的。交互性有助于这一点,但我会考虑把它分成多个图表。我不确定是否可以扩展图例以显示隐藏的81个条目。再次检查长纬度位置是否与您正在使用的世界地图投影正确对应,当我更改投影时,它们似乎在移动


相关问题 更多 >

    热门问题