GeezerVison is showing github.com — legend(labels, keywords) overload · lava/matplotlib-cpp@78fa91b
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: examples/basic.cpp +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -34,8 +34,8 @@ int main() |
34 | 34 | // Add graph title |
35 | 35 | plt::title("Sample figure"); |
36 | 36 |
|
37 | | - // Enable legend. |
38 | | - plt::legend(); |
| 37 | + // Enable legend, with explicit labels for the three lines. |
| 38 | + plt::legend(std::vector<std::string>{"sin(x)", "2", "log(x)"}); |
39 | 39 |
|
40 | 40 | // save figure |
41 | 41 | const char* filename = "./basic.png"; |
|
Collapse file
Copy file name to clipboardExpand all lines: matplotlibcpp.h +32Lines changed: 32 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1980,6 +1980,38 @@ inline void legend(const std::map<std::string, std::string>& keywords) |
1980 | 1980 | Py_DECREF(res); |
1981 | 1981 | } |
1982 | 1982 |
|
| 1983 | +template<typename StringType> |
| 1984 | +inline void legend(const std::vector<StringType>& labels, const std::map<std::string, std::string>& keywords = {}) |
| 1985 | +{ |
| 1986 | + detail::_interpreter::get(); |
| 1987 | + |
| 1988 | + PyObject* llist = PyList_New(labels.size()); |
| 1989 | + if(!llist) throw std::runtime_error("Couldn't allocate labels list in legend()."); |
| 1990 | + |
| 1991 | + for(size_t i = 0; i < labels.size(); ++i) { |
| 1992 | + PyList_SetItem(llist, i, PyString_FromString(std::string(labels[i]).c_str())); |
| 1993 | + } |
| 1994 | + |
| 1995 | + PyObject* args = PyTuple_New(1); |
| 1996 | + PyTuple_SetItem(args, 0, llist); |
| 1997 | + |
| 1998 | + // construct keyword args |
| 1999 | + PyObject* kwargs = PyDict_New(); |
| 2000 | + for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) |
| 2001 | + { |
| 2002 | + PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str())); |
| 2003 | + } |
| 2004 | + |
| 2005 | + PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_legend, args, kwargs); |
| 2006 | + |
| 2007 | + Py_DECREF(args); |
| 2008 | + Py_DECREF(kwargs); |
| 2009 | + |
| 2010 | + if(!res) throw std::runtime_error("Call to legend() failed."); |
| 2011 | + |
| 2012 | + Py_DECREF(res); |
| 2013 | +} |
| 2014 | + |
1983 | 2015 | template<typename Numeric> |
1984 | 2016 | inline void set_aspect(Numeric ratio) |
1985 | 2017 | { |
|