如何用R语言Highcharts在世界地图展示各国多组碳排放占比数据
解决R Highcharts地图仅显示最后一组排放数据的问题
你当前通过多次调用hc_add_series_map添加多个排放类别系列的方式,会导致后续系列覆盖前序系列——因为Highcharts地图系列无法在同一图层叠加多类别数据。要实现每个国家展示所有排放占比的效果,可按以下方案修改:
核心思路
保留数据的宽格式(包含所有*_percent字段),仅添加一个地图系列,通过自定义Tooltip展示所有类别的占比数据;若需要切换不同类别的地图颜色显示,可添加动态切换功能。
方案1:单系列地图+Tooltip展示所有占比
选择某一排放类别作为地图颜色的基准,然后自定义Tooltip模板,鼠标悬停时显示该国家所有排放类别的占比:
# 加载必要包 library(highcharter) library(dplyr) highchart() %>% # 仅添加一个地图系列,选择coal_percent作为颜色基准 hc_add_series_map( worldgeojson, df = all_emissions_percent, value = "coal_percent", name = "CO2 Emissions", joinBy = "name" ) %>% # 自定义Tooltip,展示所有排放类别占比 hc_tooltip( formatter = JS("function() { return `<b>${this.point.name}</b><br/> 煤炭: ${this.point.coal_percent}%<br/> 石油: ${this.point.oil_percent}%<br/> 天然气: ${this.point.gas_percent}%<br/> 水泥: ${this.point.cement_percent}%<br/> 燃烧放空: ${this.point.flaring_percent}%<br/> 其他: ${this.point.other_percent}%`; }") ) %>% hc_colorAxis(stops = stops) %>% hc_title(text = "各国CO2排放占比") %>% hc_legend(enabled = TRUE)
方案2:添加类别切换功能(可选)
如果需要切换不同类别对应的地图颜色,可通过动态修改系列的value字段实现,添加下拉菜单供用户选择:
highchart() %>% hc_add_series_map( worldgeojson, df = all_emissions_percent, value = "coal_percent", name = "煤炭排放占比", joinBy = "name", id = "emission-series" # 给系列设置ID,方便后续修改 ) %>% hc_tooltip( formatter = JS("function() { return `<b>${this.point.name}</b><br/> 煤炭: ${this.point.coal_percent}%<br/> 石油: ${this.point.oil_percent}%<br/> 天然气: ${this.point.gas_percent}%<br/> 水泥: ${this.point.cement_percent}%<br/> 燃烧放空: ${this.point.flaring_percent}%<br/> 其他: ${this.point.other_percent}%`; }") ) %>% hc_colorAxis(stops = stops) %>% hc_title(text = "各国CO2排放占比") %>% # 添加下拉菜单切换显示类别 hc_chart( events = list( load = JS("function() { var chart = this; // 定义类别字段和显示名称 var categories = ['coal_percent', 'oil_percent', 'gas_percent', 'cement_percent', 'flaring_percent', 'other_percent']; var names = ['煤炭', '石油', '天然气', '水泥', '燃烧放空', '其他']; // 创建下拉菜单 var select = document.createElement('select'); select.style.position = 'absolute'; select.style.top = '10px'; select.style.left = '10px'; // 填充选项 categories.forEach(function(cat, i) { var option = document.createElement('option'); option.value = cat; option.textContent = names[i]; if (i === 0) option.selected = true; select.appendChild(option); }); // 切换逻辑 select.onchange = function() { var selectedIdx = categories.indexOf(this.value); chart.series[0].update({ value: this.value, name: names[selectedIdx] + '排放占比' }); chart.colorAxis[0].update({}); // 更新颜色轴适配新数据 }; // 将菜单添加到图表容器 chart.renderTo.appendChild(select); }") ) )
关键注意点
- 不要多次调用
hc_add_series_map:地图系列属于同一图层,后续添加的系列会覆盖前序系列,这是你当前仅看到最后一组数据的原因。 - 自定义Tooltip是核心:通过JavaScript模板,可以灵活展示每个国家的所有排放占比数据,满足你查看全类别信息的需求。
内容的提问来源于stack exchange,提问作者Shashivydyula
相关产品推荐
相关产品推荐

