[英]How to pass a variable from c# into javascript for plotting in plotly.js
我试图将在 c# 中生成的 X 和 Y 数据传递到 plotly.js,每秒更新一次(或尽可能以编程方式更新)。 我将如何在 javascript 中引用位于 .json 文件或 c# 中的像 x 和 y 这样的变量? 最终,javascript 部分应该使用从 c# 代码中提取的 x 和 y 运行(或者在 c# 中,我可以每秒生成一个 .json 文件)。 Plotly 允许动态更新,因此如果可以传递变量,这应该是可能的。 我在下面列出了我的起点:
C# 代码:
dataPoint.X = 0;
dataPoint.Y = retrieveVariable(MachineInfoService.Instance.machineInfo.plot, 0);
xstr = dataPoint.X.ToString();
ystr = dataPoint.Y.ToString();
for (i = 1; i < numdataPoints; i++)
{
dataPoint.X = i;
dataPoint.Y = retrieveVariable(MachineInfoService.Instance.machineInfo.plot, i);
xstr =xstr +", " +dataPoint.X.ToString();
ystr = ystr +", "+ dataPoint.Y.ToString();
Globals.PlotlyX = xstr;
Globals.PlotlyY = ystr;
graphData.Add(dataPoint);
}
webView.Navigate(new Uri("ms-appx-web:///Assets/index3.html"));
index3.html:
<html>
<head>
<!-- Plotly.js -->
<!----<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> -->
<script src="plotly-latest.min.js"></script>
<script type="text/javascript" src="../Assets/xydata.json"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<!-- Plotly chart will be drawn inside this DIV -->
<div id="graphDiv"></div>
<script>
jQuery.get('../Assets/xydata.json');
Plotly.newPlot('plotly-chart', data, layout);
</script>
</body>
</html>
xydata.json:
{
"data": [
{
"x": [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ],
"y": [ 0, 3, 6, 4, 5, 2, 3, 5, 4 ],
"type": "scatter",
"name": "Plot 1"
},
{
"x": [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ],
"y": [ 0, 4, 7, 8, 3, 6, 3, 3, 4 ],
"type": "scatter",
"name": "Plot 2"
},
{
"x": [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ],
"y": [ 0, 5, 3, 10, 5.33, 2.24, 4.4, 5.1, 7.2 ],
"type": "scatter",
"name": "Plot 3"
}
],
"layout": {
"showlegend": true,
"legend": { "orientation": "h" }
}
}
我不会为每个绘图更新写入文件。 最干净的方法可能是使用Newtonsoft 的 Json.NET ,它可以帮助您将 .NET 对象转换为 JSON。 如果您不想使用其他库,您也可以手动将字符串格式化为有效的 JSON,但这可能会更加复杂/容易出错。
有了新的绘图数据后,通过 C# 调用该函数,如下所示:
PlotyObject data = new PlotyObject()
webView.Document.InvokeScript("updatePlotWithNewData", {JsonConvert.SerializeObject(data)})
或者
webView.Document.InvokeScript("updatePlotWithNewData", {"{...manually formatted JSON...}"})
在您的index3.html
文件中,您可以执行以下操作来接受新数据并更新 Ploty 图表:
<script>
var plotlyData = {...}
var layout = { ... }
$(document).ready(function() {
Plotly.newPlot('plotly-chart', plotlyData, layout);
});
function updatePlotWithNewData(newData) {
plotlyData = JSON.parse(newData);
Plotly.redraw('plotly-chart');
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.