Skip to content

Commit 3302036

Browse files
committed
matplotlibcpp.h: add legend() function that takes as input the list of labels
1 parent 6be6a2a commit 3302036

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

datetime_utils.h

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,6 @@ PyObject* toPyDateTimeList(const Time_t* t, size_t nt)
5050
PyObject* tlist = PyList_New(nt);
5151
if(tlist == nullptr) return nullptr;
5252

53-
// Py_INCREF(tlist);
54-
5553
if(!PyDateTimeAPI) { PyDateTime_IMPORT; }
5654

5755
for(size_t i = 0; i < nt; i++) {

matplotlibcpp.h

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
#if PY_MAJOR_VERSION >= 3
3838
#define PyString_FromString PyUnicode_FromString
3939
#define PyInt_FromLong PyLong_FromLong
40-
#define PyString_FromString PyUnicode_FromString
4140
#endif
4241

4342
#define CPP20 202002L
@@ -2424,6 +2423,46 @@ namespace matplotlibcpp
24242423
Py_DECREF(res);
24252424
}
24262425

2426+
template<std::ranges::contiguous_range Labels>
2427+
void legend(const Labels& labels, const std::map<std::string, std::string>& keywords={})
2428+
{
2429+
detail::_interpreter::get();
2430+
2431+
PyObject* llist = PyList_New(labels.size());
2432+
if(llist == nullptr)
2433+
throw "Can't allocate labels list in legend() function.";
2434+
2435+
// iterate over labels, hopefully not too many!
2436+
size_t i=0;
2437+
for (const auto& l : labels) {
2438+
PyObject* str = PyString_FromString(l.c_str());
2439+
PyList_SET_ITEM(llist, i++, str);
2440+
}
2441+
2442+
// construct keyword args
2443+
PyObject* kwargs = PyDict_New();
2444+
for(std::map<std::string, std::string>::const_iterator it
2445+
= keywords.begin();
2446+
it != keywords.end(); ++it) {
2447+
PyDict_SetItemString(kwargs, it->first.c_str(),
2448+
PyString_FromString(it->second.c_str()));
2449+
}
2450+
2451+
PyObject* args = PyTuple_New(1);
2452+
PyTuple_SetItem(args, 0, llist);
2453+
2454+
PyObject* res = PyObject_Call(
2455+
detail::_interpreter::get().s_python_function_legend,
2456+
args, kwargs);
2457+
// PyObject* res = PyObject_Call(
2458+
// detail::_interpreter::get().s_python_function_legend,
2459+
// detail::_interpreter::get().s_python_empty_tuple, kwargs);
2460+
if(!res) throw std::runtime_error("Call to legend() failed.");
2461+
2462+
Py_DECREF(kwargs);
2463+
Py_DECREF(res);
2464+
}
2465+
24272466
template<typename Numeric>
24282467
void set_aspect(Numeric ratio)
24292468
{

0 commit comments

Comments
 (0)