1

I would like to change the hover text that is displayed on the x-axis. I know I can change the hover text of the bar using js below

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

So how do I change the hover text for the x axis? i.e. have the 2 display as Two.

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
Douglas Woods
  • 824
  • 2
  • 9
  • 25
  • Have you seen and checked this: [Plotly: How can I change the format of hover-on labels?](http://stackoverflow.com/questions/30666214/plotly-how-can-i-change-the-format-of-hover-on-labels)? – nostradamus Sep 20 '16 at 08:48
  • 1
    Thxs, the link is more concerned with the hover text for the y values, so doesn't answer my question :-( – Douglas Woods Sep 20 '16 at 22:26

1 Answers1

3
  • The hover info for the x-axis can be found in the class axistext in its text element.
  • One can overwrite its text by calling text() with the new text as the parameter
  • The problem is that Plotly will update the text again and the old and new text will flicker
  • The solution is cloning the text element and move it to the foreground
  • Next problem is that the size is for x-values and not for the text-values. The solution here is to transform the outer path element.

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;">
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99