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

时间:2016-09-20 01:19:08

标签: plotly

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

1 个答案:

答案 0 :(得分: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);
});
&#13;
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">
&#13;
&#13;
&#13;