gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:52:36 24 4
gpt4 key购买 nike

我想向悬停时显示的 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/

关于javascript - plotly.js 如何在悬停时更改 z 数据以在色标上显示 % 和 %,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com