2016-09-20 45 views
0

我想更改x軸上顯示的懸停文本。我知道我可以改變使用下面的js酒吧的懸停文本如何使用Plotly更改x軸上的懸停文本

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

+0

你所看到的和檢查這一點:[Plotly:如何更改格式懸停在標籤上](http://stackoverflow.com/questions/30666214/ plotly知識,-I-變化最格式的懸停上的標籤即可)? – nostradamus

+0

Thxs,鏈接更關心y值的懸停文本,所以不回答我的問題:-( –

回答

1
  • x軸的懸停信息可以在文本元素中的類axistext中找到。
  • 人們可以通過調用text()新文本作爲參數
  • 的問題是,Plotly將再次更新文本和新舊文本會閃爍
  • 的解決方案是cloningtext元素和覆蓋其文本將其移動到前景
  • 下一個問題是大小是爲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;">