如何将c#中的变量传递到javascript中,以便在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。如果您不想使用另一个库,您也可以手动将String格式化为有效的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>

最新更新