|
27 | 27 | namespace matplotlibcpp {
|
28 | 28 |
|
29 | 29 | namespace detail {
|
| 30 | + static std::string s_backend; |
| 31 | + |
30 | 32 | struct _interpreter {
|
31 | 33 | PyObject *s_python_function_show;
|
32 | 34 | PyObject *s_python_function_save;
|
@@ -76,14 +78,28 @@ namespace matplotlibcpp {
|
76 | 78 | import_array(); // initialize numpy C-API
|
77 | 79 | #endif
|
78 | 80 |
|
| 81 | + PyObject* matplotlibname = PyString_FromString("matplotlib"); |
79 | 82 | PyObject* pyplotname = PyString_FromString("matplotlib.pyplot");
|
80 | 83 | PyObject* pylabname = PyString_FromString("pylab");
|
81 |
| - if(!pyplotname || !pylabname) { throw std::runtime_error("couldnt create string"); } |
| 84 | + if (!pyplotname || !pylabname || !matplotlibname) { |
| 85 | + throw std::runtime_error("couldnt create string"); |
| 86 | + } |
| 87 | + |
| 88 | + PyObject* matplotlib = PyImport_Import(matplotlibname); |
| 89 | + Py_DECREF(matplotlibname); |
| 90 | + if(!matplotlib) { throw std::runtime_error("Error loading module matplotlib!"); } |
| 91 | + |
| 92 | + // matplotlib.use() must be called *before* pylab, matplotlib.pyplot, |
| 93 | + // or matplotlib.backends is imported for the first time |
| 94 | + if (!s_backend.empty()) { |
| 95 | + PyObject_CallMethod(matplotlib, "use", "s", s_backend.c_str()); |
| 96 | + } |
82 | 97 |
|
83 | 98 | PyObject* pymod = PyImport_Import(pyplotname);
|
84 | 99 | Py_DECREF(pyplotname);
|
85 | 100 | if(!pymod) { throw std::runtime_error("Error loading module matplotlib.pyplot!"); }
|
86 | 101 |
|
| 102 | + |
87 | 103 | PyObject* pylabmod = PyImport_Import(pylabname);
|
88 | 104 | Py_DECREF(pylabname);
|
89 | 105 | if(!pylabmod) { throw std::runtime_error("Error loading module pylab!"); }
|
@@ -157,6 +173,12 @@ namespace matplotlibcpp {
|
157 | 173 | }
|
158 | 174 | };
|
159 | 175 | }
|
| 176 | + |
| 177 | + // must be called before the first regular call to matplotlib to have any effect |
| 178 | + void backend(const std::string& name) |
| 179 | + { |
| 180 | + detail::s_backend = name; |
| 181 | + } |
160 | 182 |
|
161 | 183 | bool annotate(std::string annotation, double x, double y)
|
162 | 184 | {
|
|
0 commit comments