如何使用Plotly更改x轴上的悬停文本

问题描述 投票:0回答:1

我想更改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);

enter image description here

那么如何更改x轴的悬停文本?即将2显示为Two

plotly
1个回答
2
投票
  • x轴的悬停信息可以在文本元素的类axistext中找到。
  • 可以通过使用新文本作为参数调用text()来覆盖其文本
  • 问题是Plotly将再次更新文本,旧文本和新文本将闪烁
  • 解决方案是cloning text元素并将其移动到前台
  • 下一个问题是大小是针对x值而不是针对文本值。这里的解决方案是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);
});
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">
© www.soinside.com 2019 - 2024. All rights reserved.