plotly.js 如何在悬停时更改 z 数据以在色标上显示 % 和 %

plotly.js how to change z data on hover to display % as well as % on colorscale

我想向悬停时显示的 z 值添加一个 % 标签。另外,现在,我的色阶只显示 -10 到 10,但我希望它显示 % 所以 -10% 到 10%。这是我的代码。 我尝试添加刻度后缀:“%”,但我不确定应该把它放在哪里,因为色阶似乎不是像 x 和 y 轴那样的轴。

var xValues = ['A', 'B', 'C',];

var yValues = ['W', 'X', 'Y', 'Z'];

var zValues = [[-2.45,-0.4,1.3],
          [2.9,3.9,-5.66],
          [0.5,-2.6,-3.2],
          [-8.3,-0.5,-0.1]];


var a_text = [["Comodities + producers","Consumer Discretionary","Utilities Equities"],
        ["Health and Biotech","Global Real Estate","Financial Equities"],
        ["Emerging Market Bonds","Technology Equities","Industrials Equities"],
        ["Oil and Gas","China Equities","Diversified Portfolio"]];

var data = [{

  x: xValues,
  y: yValues,
  z: zValues,
  hoverinfo: "z",
  reversescale: true,
  type: 'heatmap',
  // zsmooth: "best",
  colorscale: "Spectral",
  zauto: false,
  zmin:-10,
  zmax:10,
  showscale: true,
}];

var layout = {
  title: 'Annotated Heatmap',
  annotations: [],
  xaxis:  {
    ticks: '',
    side: 'top',
    tickfont: {color: 'rgb(255,255,255)'}
  },
  yaxis: {
    ticks: '',
    ticksuffix: ' ',
    width: 700,
    height: 700,
    autosize: true,
    tickfont: {color: 'rgb(255,255,255)'},
   }
};

for ( var i = 0; i < yValues.length; i++ ) {
  for ( var j = 0; j < xValues.length; j++ ) {
    var currentValue = (zValues[i][j]);
    if (currentValue < -0.05) {
      var textColor = 'white';
    }else{
      var textColor = 'black';
    }
    var result = {
  xref: 'x1',
  yref: 'y1',
  x: xValues[j],
  y: yValues[i],
  text: a_text[i][j],
  font: {
    family: 'Arial',
    size: 12,
    color: 'rgb(50, 171, 96)'
  },
  showarrow: false,
  font: {
    color: textColor
  }
};
layout.annotations.push(result);
  }
}

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

您需要更改两件事,颜色栏和悬停文本。

彩条

将此信息添加到您的变量 data

colorbar: {
    title: 'Relative change',
    ticksuffix: '%',
}

悬停文本

首先将 z 值转换为字符串并追加 %.

var zText = [];
var prefix = "+";
var i = 0;
var j = 0;
for (i = 0; i < zValues.length; i += 1) {
    zText.push([]);
    for (j = 0; j < zValues[i].length; j += 1) {
        if (zValues[i][j] > 0) {
            prefix = "+";
        } else {
            prefix = "";
        }
        zText[i].push(prefix + zValues[i][j] + "%");
    }
}

然后将新文本分配给情节。 添加

text: zText,
hoverinfo: "text",

到你的变量 data.

这里是一个fiddle完整的数据和代码:https://jsfiddle.net/Ashafix/e6936boq/2/