簡體   English   中英

如何將變量從 c# 傳遞到 javascript 以在 plotly.js 中繪圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM