javascript - 如何在 plotly.js 中添加针或刻度盘来测量指示器?
问题描述
我很难将刻度盘/针从 plotly.js 添加到仪表图表。
没有针的仪表 :如上图所示,它是没有任何针的仪表图表。
带针量规 :我想构建类似于“带针量规”的东西,这让我很难过。
我的“无针/表盘仪表”代码:
`https://codepen.io/vivek137/pen/rNyembX`
解决方案
您需要在仪表图顶部添加箭头注释。我回答了一个类似的问题,在那个答案中,我描述了如何使用极坐标来找出结束位置x
和y
箭头。在引擎盖下,您制作的仪表图具有 [0,1] 的 x 范围和 [0,1] 的 y 范围,因此起点是ax=0.5
和ax=0
都是注释的参数。然后结束位置由 给出x = 0.5 + r * cos(theta)
,y = r * sin(theta)
其中 theta 是从图表右侧截取的角度并逆时针移动。
您应该记住的一件事是,如果您的浏览器中的渲染区域不是一个完美的正方形,则可能需要调整r
和值。theta
例如,在我的 codepen中,我使用r=0.7
,theta=93.5
来指向 40。
let data = [
{
mode: "gauge",
type: "indicator",
value: 40,
gauge: {
shape: "angular",
bar: {
color: "blue",
line: {
color: "red",
width: 4
},
thickness: 0
},
bgcolor: "#388",
bordercolor: "#a89d32",
borderwidth: 3,
axis: {
range: [0,100],
visible: true,
tickmode: "array",
tickvals: [5, 10, 40, 80, 100],
ticks: "outside"
},
steps: [
{
range: [0, 40],
color: "#9032a8"
}
]
}
}
]
var theta = 93.5
var r = 0.7
var x_head = r * Math.cos(Math.PI/180*theta)
var y_head = r * Math.sin(Math.PI/180*theta)
let layout = {
xaxis: {range: [0, 1], showgrid: false, 'zeroline': false, 'visible': false},
yaxis: {range: [0, 1], showgrid: false, 'zeroline': false, 'visible': false},
showlegend: false,
annotations: [
{
ax: 0.5,
ay: 0,
axref: 'x',
ayref: 'y',
x: 0.5+x_head,
y: y_head,
xref: 'x',
yref: 'y',
showarrow: true,
arrowhead: 9,
}
]
};
Plotly.newPlot('gauge1', data, layout)