我想更改x轴上显示的悬停文本。我知道我可以使用下面的js更改栏的悬停文本
var trace1 = {
x: [0, 1, 2, 3],
y: [10, 11, 21, 31],
text: ["Zero", "One", "Two", "Three"],
type: 'bar'
};
var data = [trace1];
var layout = {barmode: 'stack'};
Plotly.newPlot('myDiv', data, layout);
那么如何更改x轴的悬停文本?即将2
显示为Two
。
答案 0 :(得分:2)
axistext
中找到。text()
来覆盖其文本
text
元素并将其移至前台transform
外部path
元素。
var trace1 = {
x: [0, 1, 2, 3],
y: [10, 11, 21, 31],
text: ["Zero", "One", "Two", "Three"],
type: "bar"
};
var data = [trace1];
var layout = {barmode: "stack"};
Plotly.newPlot("myDiv", data, layout);
document.getElementById("myDiv").on("plotly_hover", function (data) {
//get correct text from trace1
var infotext = data.points.map(function (d) {
return (trace1.text[d.pointNumber]);
});
//select the old x-axis info text
var x_infotext = Plotly.d3.selectAll(".axistext").selectAll("text");
//duplicate the x-axis info text
var attr = x_infotext.node().attributes;
var attr_length = attr.length;
var node_name = x_infotext.property("nodeName");
var parent = Plotly.d3.select(x_infotext.node().parentNode);
var cloned = parent.append(node_name)
.attr("id", "real_axistext");
var j = 0;
for (j = 0; j < attr_length; j += 1) {
if (attr[j].nodeName !== "id") {
cloned.attr(attr[j].name, attr[j].value);
}
}
//rescale the new info text
Plotly.d3.selectAll(".axistext").selectAll("path").node().setAttribute("transform", "scale(5,1)");
//assign the correct text to the next x-axis info text
cloned.text(infotext);
cloned.style("opacity", 1);
//hide the old info text
x_infotext.style("opacity", 0);
});
&#13;
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">
&#13;