如何使用javascript在plotly中旋转数据点的文本标签

Posted

技术标签:

【中文标题】如何使用javascript在plotly中旋转数据点的文本标签【英文标题】:How to rotate text labels for data points in plotly using javascript 【发布时间】:2021-11-03 17:35:38 【问题描述】:

我想要一行带有文本标签的数据点。我似乎无法正常工作。

这是我尝试过的一个示例。然而,结果是文本是水平的而不是垂直的......

这只能通过注释实现吗?还是有更直接的方法(在数据本身中)?

var trace1 = 
  x: [0, 1, 2],
  y: [1, 1, 1],
  mode: 'lines+markers+text',
  name: 'Lines, Markers and Text',
  text: ['Text A', 'Text B', 'Text C'],
  textposition: 'top',
  angle: 90, // NOT WORKING
  type: 'scatter'
;
var data = [trace1];
var layout = showlegend: false;
Plotly.newPlot('myDiv', data, layout);
<head>
    <!-- Load plotly.js into the DOM -->
    <script src='https://cdn.plot.ly/plotly-2.4.2.min.js'></script>
</head>

<body>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>

【问题讨论】:

【参考方案1】:

很遗憾,您无法在跟踪中指定 textangle 以进行分散。如您所说,textangle 只能使用annotations 进行修改。

这里有一个小例子说明你可以做什么,循环坐标使注释更容易构造(codepen 是here):

var trace1 = 
  x: [0, 1, 2],
  y: [1, 1, 1],
  mode: 'lines+markers',
  type: 'scatter'
;

var data = [trace1];
var coordinates = [[0, 1, 2],[1, 1, 1]]
var text = ['Text A', 'Text B', 'Text C']
var annotations = []

for (let i = 0; i<coordinates[0].length; i++) 
  annotations.push(
    x: coordinates[0][i],
    y: coordinates[1][i],
    text: text[i],
    textangle: 90,
    showarrow: false
  )


var layout = showlegend: false, annotations: annotations;
Plotly.newPlot('myDiv', data, layout);

【讨论】:

与此同时,我确实使用注释解决了它。谢谢@Derek O!

以上是关于如何使用javascript在plotly中旋转数据点的文本标签的主要内容,如果未能解决你的问题,请参考以下文章

Plotly React 在重新渲染之间保持缩放和旋转

使用 plotly 进行三元图旋转

如何旋转 xtick 标签条形图 plotly express?

如何使用 Plotly Javascript 显示循环进度图

Plotly Graphs - Javascript 和 Jinja 之间的冲突

如何更改使用 Plotly Express 创建的堆积条形图的文本方向?