如何改变z数据悬停显示百分比以及百分比的颜色

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

本文关键字:百分比 显示 颜色 悬停 数据 何改变 改变      更新时间:2023-09-26

我想添加一个%标签的z值,是显示在悬停。同样,现在,我的色阶只显示-10到10,但我希望它显示%,所以-10%到10%。这是我的密码。我试着添加ticksuffix:"%",但我不确定我应该把它放在哪里,因为它看起来像色阶不是像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

下面是完整的数据和代码:https://jsfiddle.net/Ashafix/e6936boq/2/