首页 > 解决方案 > 如何将一个技巧的长标签分成多行?

问题描述

我利用 plot.ly 向我的用户显示图表。但是 X 轴的标签太长了。发生的情况是最后一个柱的标签在图表之外并且不可见。因此,我想将它们分成多行,以便更容易阅读。有没有办法通过 plot.ly 配置来解决这个问题?

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

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

标签: javascriptplotly

解决方案


您可以将跟踪传递给一个可以为您进行包装的函数,因为我无法找到一个情节严重的解决方案,所以我提供了这个替代方案,基本上,我访问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>


推荐阅读