-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTestMatplotlib.cs
More file actions
105 lines (94 loc) · 3.29 KB
/
Copy pathTestMatplotlib.cs
File metadata and controls
105 lines (94 loc) · 3.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using Python.Runtime;
using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Media.Imaging;
namespace Test
{
public class TestMatplotlib
{
public static void SetUp(string backend)
{
using (Py.GIL())
{
Numpy.Initialize();
Matplotlib.Initialize(backend);
//PythonEngine.Exec("import matplotlib;print(matplotlib.get_backend())");
Console.WriteLine(Matplotlib.get_backend());
}
}
public static void Plot()
{
using (Py.GIL())
{
dynamic plt = Py.Import("matplotlib.pylab");
dynamic np = Py.Import("numpy");
var x = Numpy.NewArray(new double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 });
var y = np.sin(x);
//plt.plot(x);
plt.figure();
//plt.scatter(x, y);
plt.show();
}
using (Py.GIL())
{
var scope = Py.CreateScope();
var np = scope.Import("numpy", "np");
var plt = scope.Import("matplotlib.pylab", "plt");
var x = Numpy.NewArray(new double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 });
var y = np.sin(x);
scope.Set("x", x);
scope.Set("y", y);
//directly plot
plt.plot(x, y);
plt.show();
//use python slice grammer
scope.Exec(
"fig = plt.figure() \n" +
"plt.plot(x[1:], y[1:]) \n" +
"plt.show()"
);
}
}
static AutoResetEvent mEvent = new AutoResetEvent(false);
public static void PlotInWindow()
{
byte[] plotdata;
using (Py.GIL())
{
var scope = Py.CreateScope();
var np = scope.Import("numpy", "np");
var plt = scope.Import("matplotlib.pylab", "plt");
var x = Numpy.NewArray(new double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 });
var y = np.sin(x);
scope.Set("x", x);
scope.Set("y", y);
scope.Exec(
"fig = plt.figure() \n" +
"plt.plot(x[1:], y[1:]) \n"
);
var fig = scope.Get("fig");
plotdata = Matplotlib.SaveFigureToArray(fig, 200, "png");
}
Stream stream = new MemoryStream(plotdata);
Thread th = new Thread(
() => {
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
var img1 = new System.Windows.Controls.Image();
img1.Source = bitmapImage;
Window window = new Window();
window.Content = img1;
window.ShowDialog();
mEvent.Set();
}
);
th.SetApartmentState(ApartmentState.STA);
th.Start();
mEvent.WaitOne();
}
}
}