我想将%标记添加到悬停时显示的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);
答案 0 :(得分:2)
您需要更改两个内容,颜色栏和悬停文本。
将此信息添加到变量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/