使用链接到 Altair 中新类别的 Transform_calculate 时对图例进行排序时出现问题

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

我正在尝试订购两个或更多串联的分区统计图的图例,这些图例是使用字符串字典进行标记的。他们分享着传奇。然而,当连接它们时,图例没有排序,本应是第一个类别的内容最终成为最后一个类别。当只制作一张地图时,代码工作正常。enter image description here我应该如何解决这个问题?

import altair as alt
import geopandas as gpd
import pickle
import requests


resp = requests.get("https://raw.githubusercontent.com/ccsuehara/cfi/main/mapping.pickle")
mapping = pickle.loads(resp.content)
srcs = gpd.read_file("https://raw.githubusercontent.com/ccsuehara/cfi/main/example.geojson")


base = alt.Chart(srcs).mark_geoshape().properties(
    width=400,
    height=400
).project(
    type='mercator'  
)

g_ = alt.concat(
    base.encode(
    color=alt.Color(
        'disp_2010:N',
        scale=alt.Scale(scheme='greens'),
        title = "% Change (winsor)",
        sort=alt.EncodingSortField('class_2010_win',  order='ascending')
       ),
    ).transform_filter(
        'isValid(datum.class_2010_win)'
    ).transform_calculate(
        disp_2010=f"{mapping}[datum.class_2010_win]"
    ).properties(
        title="Δ 2005 - 2010(%)"
    )    | base.encode(
    color=alt.Color(
        'disp_2015:N',
        scale=alt.Scale(scheme='greens'),
      title = "% Change (winsor)",
     #sort=alt.EncodingSortField('class_2010_win',  order='ascending')
      ),
    ).transform_filter(
        'isValid(datum.class_2015_win)'
    ).transform_calculate(
        disp_2015=f"{mapping}[datum.class_2015_win]",
    ).properties(
        title="Δ 2010 - 2015(%)"
    )
)

g_
vega-lite altair choropleth
1个回答
0
投票

最简单的方法是将数据转换为长格式,然后使用分面来创建两个图表。不幸的是,目前存在一个 vega-lite bug,它阻止分面处理 mark_geoshape 图,但我们仍然可以通过串联和长格式数据来实现您想要的目标。

我已经在 pandas 中完成了长格式的转换,但在 Altair 中也可以使用

transform_fold
函数实现。

import altair as alt
import geopandas as gpd
import pickle
import requests

resp = requests.get("https://raw.githubusercontent.com/ccsuehara/cfi/main/mapping.pickle")
mapping = pickle.loads(resp.content)
srcs = gpd.read_file("https://raw.githubusercontent.com/ccsuehara/cfi/main/example.geojson")

new_srcs = srcs.melt(id_vars=['geometry'], var_name='year', value_name='win').dropna()
new_srcs['Period'] = new_srcs['year'].map({'class_2010_win': 'Δ 2005 - 2010(%)', 'class_2015_win': 'Δ 2010 - 2015(%)'})
new_srcs['Change'] = new_srcs['win'].map(mapping)

new_base = alt.Chart(new_srcs).mark_geoshape().encode(
    color=alt.Color('Change:N', scale=alt.Scale(scheme='greens'), title="% Change (winsor)", sort=alt.EncodingSortField('win',  order='ascending')),
    tooltip=['Change', 'Period'],
).project('mercator')

new_base.transform_filter(
    alt.datum.year == 'class_2010_win'
).properties(title='Δ 2005 - 2010(%)') | new_base.transform_filter(
    alt.datum.year == 'class_2015_win'
).properties(title='Δ 2010 - 2015(%)')

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.