网站搜索

angular - Plotly.js 在悬停时显示轨迹名称不完整


我在 Angular 应用中使用 Plotly 制作了一个图表,但这个轨迹有一个很长的名字。所以当我悬停在图表上时,名字会被缩短,并在后面加上…。我真的不想这样。我该如何更改这个情况?

这是我的代码。

 var text = "Plot_ForecastConfig";
    var layout = {
      showlegend: true,
      legend: {"orientation": "h"},
      yaxis: {
        title: 'Sales',
        titlefont: {
          family: 'Courier New, monospace',
          size: 18,
          color: '#7f7f7f'
        }
      }
    };
    var options = {
      scrollZoom: true,
      showLink: false,
      modeBarButtonsToAdd: [{
        name: 'image',
        title: 'Download plot as a png',
        icon: Plotly.Icons.camera,
        click: function () {
          Plotly.downloadImage(document.getElementById('graph'), {
            filename: text,
            format: 'png',
            height: 700,
            width: 1000
          });
        }
      }],
      modeBarButtonsToRemove: ['toImage', 'zoom2d', 'pan', 'pan2d', 'sendDataToCloud', 'hoverClosestCartesian', 'autoScale2d'],
      displaylogo: false,
      displayModeBar: true,
    };

    Plotly.newPlot('graph', this.drawing, layout, options);

答案#1

我只需在我的跟踪对象中添加以下一行,就可以显示长名称。

hoverlabel: {namelength :-1}

这是一个可行的例子。

Plotly.plot('graph', [{
  y: [2,1,2],
  name: 'loooooooooooooooooooooooooong text name',
  hoverinfo: "y+name",
  hoverlabel: {namelength :-1},
}])
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="graph"></div>

答案#2

Plotly 有一个新的属性 namelength 可以用来实现这个目的,参见 Rajshekar Reddy 的另一个答案。

namelength(整数或大于等于 -1 的整数数组)

设置此跟踪在悬停标签中跟踪名称的长度(以字符数计)。

-1 无论长度如何都显示完整名称。

0-3 显示前 0-3 个字符,且

一个大于3的整数如果小于该数字的字符数,将显示完整名称,但如果更长,将截断为namelength - 3个字符并添加省略号。

如果你想手动操作,下面的解决方案仍然有效。

你可以将轨迹 name 也分配给 text,并将 hoverinfo 设置为 x+y+text,或者自己修改 hovertext 对象(在此处可以找到更详细的解释)。

var _this = {
  drawing: [{
    x: [1, 2, 3],
    y: [1, 2, 5],
    text: "Yeah, that's a really long name, let's see what Plotly does to it",
    name: "Yeah, that's a really long name, let's see what Plotly does to it",
    hoverinfo: "x+y+name"
  }]
};

var myPlot = document.getElementById('graph1');
Plotly.newPlot(myPlot, _this.drawing);
_this.drawing[0].hoverinfo = 'x+y+text';
Plotly.newPlot('graph2', _this.drawing);


myPlot.on('plotly_hover', function(data) {
  var infotext = data.points.map(function(d) {

    if (d.x > 1) {
      return d.data.name;
    } else {
      return "";
    }
  });

  if (infotext[0] === "") {
    return;
  }
  var hoverinfo = Plotly.d3.selectAll('.hovertext').selectAll('.name');
  var cloned = Plotly.d3.selectAll('.hovertext').append(hoverinfo.property("nodeName"));
  var attr = hoverinfo.node().attributes;
  for (var j = 0; j < attr.length; j += 1) {
    cloned.attr(attr[j].name, attr[j].value);
  }
  cloned[0][0].innerHTML = infotext[0];
  hoverinfo.attr('opacity', 0);
  cloned.attr('opacity', 1);
});
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<div id='graph1'></div>
<div id='graph2'></div>