Skip to content

Commit 5b1c7bb

Browse files
author
Benno Evers
committed
Add backend function to enable running in headless mode.
1 parent 598aa8e commit 5b1c7bb

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

matplotlibcpp.h

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
namespace matplotlibcpp {
2828

2929
namespace detail {
30+
static std::string s_backend;
31+
3032
struct _interpreter {
3133
PyObject *s_python_function_show;
3234
PyObject *s_python_function_save;
@@ -76,14 +78,28 @@ namespace matplotlibcpp {
7678
import_array(); // initialize numpy C-API
7779
#endif
7880

81+
PyObject* matplotlibname = PyString_FromString("matplotlib");
7982
PyObject* pyplotname = PyString_FromString("matplotlib.pyplot");
8083
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+
}
8297

8398
PyObject* pymod = PyImport_Import(pyplotname);
8499
Py_DECREF(pyplotname);
85100
if(!pymod) { throw std::runtime_error("Error loading module matplotlib.pyplot!"); }
86101

102+
87103
PyObject* pylabmod = PyImport_Import(pylabname);
88104
Py_DECREF(pylabname);
89105
if(!pylabmod) { throw std::runtime_error("Error loading module pylab!"); }
@@ -157,6 +173,12 @@ namespace matplotlibcpp {
157173
}
158174
};
159175
}
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+
}
160182

161183
bool annotate(std::string annotation, double x, double y)
162184
{

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy