如何将花样的长标签分成多行?

时间:2019-05-04 17:20:20

标签: javascript plotly

我利用plot.ly向用户显示图形。但是X轴的标签太长。发生的情况是最后一个条的标签在图形外部并且不可见。因此,我想将它们分成多行,以便更容易阅读。使用plot.ly配置是否可以实现此目的?

在x轴上带有长标签的当前图形:

current graph with long labels on x-axis

1 个答案:

答案 0 :(得分:0)

您可以将迹线传递到可以为您包装的函数中,因为我找不到情节解决方案,因此我提供了这种替代方法,基本上,我访问了每个迹线的x属性,然后使用正则表达式添加<br>,请检查以下示例,如果您有任何疑问或问题,请告诉我。

var trace1 = {
	x: [
		"this is a very long title that needs to be wrapped up for readability purposes2",
		"this is a very long title that needs to be wrapped up for readability purposes2",
		"this is a very long title that needs to be wrapped up for readability purposes3"
	],
	y: [90, 40, 60],
	type: "bar",
	name: "New York Zoo"
};

var trace2 = {
	x: [
		"this is a very long title that needs to be wrapped up for readability purposes",
		"this is a very long title that needs to be wrapped up for readability purposes2",
		"this is a very long title that needs to be wrapped up for readability purposes3"
	],
	y: [10, 80, 45],
	type: "bar",
	name: "San Francisco Zoo"
};
addBreaksAtLength = 10;
textwrapper = function(traces) {
	for (trace of traces) {
		trace.x = trace.x.map(text => {
			let rxp = new RegExp(".{1," + addBreaksAtLength + "}", "g");
			return text.match(rxp).join("<br>");
		});
	}
	return traces;
};
var data = textwrapper([trace1, trace2]);
var layout = {
	title: "Hide the Modebar",
	showlegend: true
};
Plotly.newPlot("myDiv", data, layout, { displayModeBar: false });
<head>
  <!-- Plotly.js -->
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<div id="myDiv" style="width:100%;"></div>