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

Knime中使用Plotly绘制choroplethmap(分级统计图)时,如何在区域上方添加固定可见标签?

Knime中使用Plotly绘制choroplethmap(分级统计图)时,如何在区域上方添加固定可见标签?

嗨,我看了你的代码,问题其实出在几个容易忽略的小细节上,调整一下就能让固定文本标签正常显示在地图上啦!

问题1:经纬度取值搞反了

你定义的stateCoords里,每个州的坐标格式是[经度, 纬度],但在scattergeo的配置中,你把lat(纬度)和lon(经度)的取值逻辑搞反了。正确的写法应该是:

lon: states.map(state => stateCoords[state][0]), // 取坐标数组的第一个值(对应经度)
lat: states.map(state => stateCoords[state][1]), // 取坐标数组的第二个值(对应纬度)

问题2:地图布局配置写错了字段

你原来的layout里用了map字段,但Plotly的地理坐标系配置是在geo字段下的,map是无效的,所以地图的中心、缩放级别等设置都不会生效,得改成layout.geo。

问题3:未共用同一个Geo实例

你的choroplethmap图层没有指定geo: 'geo'属性,但scattergeo图层指定了,这会导致两个图层使用的不是同一个地理坐标系,文本标签可能会出现在错误的位置。所以需要给choroplethmap也加上geo: 'geo',让它们绑定到同一个geo配置上。

修正后的完整代码

var body = document.getElementsByTagName('body')[0];
var html = '<div id="myDiv">';
body.innerHTML = html;

var stateCoords = { 
    "opolskie": [17.9213, 50.6751],  
    "łódzkie": [19.4560, 51.7594]
};

var states = ["opolskie", "łódzkie"];

var data = [
  {
    type: "choroplethmap", 
    name: "asd", 
    geo: 'geo', // 新增:绑定到共用的geo实例
    geojson: "https://raw.githubusercontent.com/ppatrzyk/polska-geojson/master/wojewodztwa/wojewodztwa-min.geojson", 
    locations: states,
    z: [141, 140],  
    text: [ "test text1", "test text2" ],  // Labels for hover
    featureidkey: "properties.nazwa",
    colorbar: { title: 'Value' },
    zmin: 25, 
    zmax: 280, 
    colorscale: 'Viridis'
  },
  {
    type: 'scattergeo',
    geo: 'geo',  
    lon: states.map(state => stateCoords[state][0]), // 修正:取经度(第一个值)
    lat: states.map(state => stateCoords[state][1]), // 修正:取纬度(第二个值)
    text: states,
    mode: 'text',
    textposition: 'top center', // 可选:调整文本位置,让标签更贴合区域
    textfont: {
        size: 14,
        color: 'black',
        weight: 'bold'
    }
  }
];

var layout = {
  geo: { // 修正:将map改为geo,配置共用的地理坐标系
    style: "light", 
    center: {lon: 19, lat: 52}, 
    zoom: 5.6
  },
  width: 1000, 
  height: 700, 
  margin: { t: 0, b: 0 }
};

Plotly.newPlot('myDiv', data, layout);

另外,我还加了textposition: 'top center'的配置,你可以根据实际效果调整这个值(比如'middle right'),让文本标签的位置更贴合对应州的区域。

这样调整后,固定的文本标签就会准确显示在对应的州区域上方,和你想要的效果一致啦~

备注:内容来源于stack exchange,提问作者argh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:35:27