我正在使用plotly.js来创建图表。有些图表在图例中有长文本,因此这些文字使图例变得更大。我想给图例固定宽度,如果文本长度很长,我希望它被包装。
我一直试图通过操纵DOM上的svg元素来做到这一点,但由于图例是textLength
标记,我实际上做不了多少。我也尝试将<text>
提供给 [WebMethod]
public static string TestConnection(string server)
{...}
,但它确实包装了文本,但它没有换行。
有没有办法给予图例固定宽度?
答案 0 :(得分:0)
也许只是添加到图例文本就可以轻松获得固定宽度的解决方案? 您可以在Javascript中使用任何文本换行技巧来执行此操作,例如
for (i = 0; i < data.length; i += 1) {
data[i].name = data[i].name.replace(/([\w\s,]{13,}?)\s?\b/g, "$1</br>");
}
var numbers = [];
var total = 10000;
var i = 0;
var data = [];
for (i = 0; i < total; i++) {
numbers[i] = ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3;
}
data.push({
x: numbers,
name: "that's a histogram with lots of points, it therefore needs lots of text as well",
type: 'histogram',
marker: {color: 'blue'}
});
numbers = [];
for (var i = 0; i < total; i++) {
numbers[i] = 0.25 + ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3;
}
data.push({
x: numbers,
name: "that's yet another histogram with lots of points, it therefore needs lots of text as well, like for example that it was shifted by 0.25",
type: 'histogram',
marker: {color: 'red'}
});
for (i = 0; i < data.length; i += 1) {
data[i].name = data[i].name.replace(/([\w\s,]{13,}?)\s?\b/g, "$1</br>");
}
Plotly.newPlot('myDiv', data, {showlegend: true});
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>
答案 1 :(得分:0)
Maximilian 的回答几乎适用于当前版本的 Plotly.js。似乎没有用于设置图例宽度的属性,但您可以通过将中断 (</br>
) 手动插入图例文本来对其进行装配。然而,出于某种原因,Plotly 似乎对文本中的第一个中断处理不当;为了解决这个问题,您可以在文本的开头添加一个“幽灵”中断。例如:
// Rudimentary function to break a string on spaces
// attempting to get no more than `maxChars` characters in a line
const breakString = (str, maxChars) => {
if (str.length > maxChars && str.includes(' ')) {
let index = str.lastIndexOf(' ', maxChars);
if (index === -1) index = str.indexOf(' ', maxChars + 1);
return str.substr(0, index) + '</br>' + breakString(str.substr(index + 1), maxChars);
} else {
return str;
}
}
const original_text = "Respondents who think Tenet is Christopher Nolan's most interesting movie";
const final_text = '</br>' + breakString(original_text, 20);
默认情况下,每个图例条目旁边的颜色符号与相应文本的中心对齐;对于多行图例文本,您可能希望将符号更改为与文本顶部对齐。为此,请将 this 添加到您的 layout
:
legend: {
valign: 'top',
}