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

如何转换国家缩写为全称并使用Vega-Lite绘制薪资热力世界地图

问题解答:Vega-Lite绘制薪资密度世界地图

一、之前代码报错的核心原因

Vega-Lite默认依赖的世界地理数据(比如官方的world-110m)只识别标准国家全名或ISO 3166规范的两位大写代码(如RU、NZ),而你的数据用的是小写/非标准缩写(如Ru),导致地理数据无法匹配,触发报错。

二、国家缩写转全名的方法

1. 手动映射(小数据量适用)

自己做一个缩写对应全名的字典,预处理数据时替换:

// JavaScript示例
const countryMap = {
  "Ru": "Russian Federation",
  "NZ": "New Zealand",
  "US": "United States",
  // 补充其他缩写的对应关系
};
// 批量替换数据中的缩写
yourData.forEach(item => {
  item.countryFullName = countryMap[item.countryAbbr] || item.countryAbbr;
});

2. 第三方工具批量转换(大数据量适用)

  • Python用pycountry库:
import pycountry

def convert_abbr(abbr):
    try:
        # 先把缩写转大写,匹配ISO标准
        return pycountry.countries.get(alpha_2=abbr.upper()).name
    except:
        # 处理无法匹配的异常情况
        return "未知国家"

# 假设你的数据存在DataFrame的country_abbr列
df['country_full'] = df['country_abbr'].apply(convert_abbr)
  • JavaScript用country-list库:
const { getName } = require('country-list');

// 转大写后匹配
const fullName = getName('RU'); // 返回"Russia"

三、转换全名后绘制薪资密度地图的完整示例

以下是直接可用的Vega-Lite配置,通过颜色深浅展示薪资高低(颜色越深=薪资越高):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "title": "世界各国平均薪资分布图",
  "width": 800,
  "height": 500,
  // 加载官方世界地理数据
  "data": {
    "url": "https://vega.github.io/vega-datasets/data/world-110m.json",
    "format": {"type": "topojson", "feature": "countries"}
  },
  // 关联你的薪资数据
  "transform": [
    {
      "lookup": "properties.name", // 地理数据中的国家名字段
      "from": {
        "data": {
          "url": "你的薪资数据文件路径.csv", // 替换成你的数据地址
          "format": {"type": "csv"}
        },
        "key": "国家全名", // 你的数据中存储全名的字段名
        "fields": ["平均薪资"] // 需要关联的薪资字段
      }
    }
  ],
  // 地图标记样式
  "mark": {"type": "geoshape", "stroke": "#ffffff", "strokeWidth": 0.5},
  // 颜色编码映射薪资
  "encoding": {
    "color": {
      "field": "平均薪资",
      "type": "quantitative",
      "title": "平均薪资",
      "scale": {"type": "linear", "scheme": "blues"}, // 蓝色系,深=高薪资
      "legend": {"orient": "bottom-right", "titleFontSize": 12}
    },
    // 鼠标悬停显示详情
    "tooltip": [
      {"field": "properties.name", "title": "国家"},
      {"field": "平均薪资", "title": "平均薪资"}
    ]
  },
  // 地图投影方式
  "projection": {"type": "equirectangular"}
}

配置要点:

  1. 确保你的薪资数据中,国家全名和地理数据的properties.name完全匹配(比如“Russian Federation”对应俄罗斯,不要写成“俄罗斯”)
  2. 颜色方案可以按需替换,比如用reds红色系,或者自定义颜色范围
  3. 如果数据是JSON格式,把format的type改成json即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:45:34