Browse Source

Added 'set_aspect' and set_aspect_equal function

Pierre Narvor 4 years ago
parent
commit
1875696c55
2 changed files with 59 additions and 0 deletions
  1. 3 0
      examples/modern.cpp
  2. 56 0
      matplotlibcpp.h

+ 3 - 0
examples/modern.cpp

@@ -24,6 +24,9 @@ int main()
 	// y must either be callable (providing operator() const) or iterable. 
 	plt::plot(x, y, "r-", x, [](double d) { return 12.5+abs(sin(d)); }, "k-");
 
+	//plt::set_aspect(0.5);
+	plt::set_aspect_equal();
+
 
 	// show plots
 	plt::show();

+ 56 - 0
matplotlibcpp.h

@@ -1857,6 +1857,62 @@ inline void legend(const std::map<std::string, std::string>& keywords)
   Py_DECREF(res);
 }
 
+template<typename Numeric>
+inline void set_aspect(Numeric ratio)
+{
+    detail::_interpreter::get();
+
+    PyObject* args = PyTuple_New(1);
+    PyTuple_SetItem(args, 0, PyFloat_FromDouble(ratio));
+    PyObject* kwargs = PyDict_New();
+
+    PyObject *ax =
+    PyObject_CallObject(detail::_interpreter::get().s_python_function_gca,
+      detail::_interpreter::get().s_python_empty_tuple);
+    if (!ax) throw std::runtime_error("Call to gca() failed.");
+    Py_INCREF(ax);
+
+    PyObject *set_aspect = PyObject_GetAttrString(ax, "set_aspect");
+    if (!set_aspect) throw std::runtime_error("Attribute set_aspect not found.");
+    Py_INCREF(set_aspect);
+
+    PyObject *res = PyObject_Call(set_aspect, args, kwargs);
+    if (!res) throw std::runtime_error("Call to set_aspect() failed.");
+    Py_DECREF(set_aspect);
+
+    Py_DECREF(ax);
+    Py_DECREF(args);
+    Py_DECREF(kwargs);
+}
+
+inline void set_aspect_equal()
+{
+    // expect ratio == "equal". Leaving error handling to matplotlib.
+    detail::_interpreter::get();
+
+    PyObject* args = PyTuple_New(1);
+    PyTuple_SetItem(args, 0, PyString_FromString("equal"));
+    PyObject* kwargs = PyDict_New();
+
+    PyObject *ax =
+    PyObject_CallObject(detail::_interpreter::get().s_python_function_gca,
+      detail::_interpreter::get().s_python_empty_tuple);
+    if (!ax) throw std::runtime_error("Call to gca() failed.");
+    Py_INCREF(ax);
+
+    PyObject *set_aspect = PyObject_GetAttrString(ax, "set_aspect");
+    if (!set_aspect) throw std::runtime_error("Attribute set_aspect not found.");
+    Py_INCREF(set_aspect);
+
+    PyObject *res = PyObject_Call(set_aspect, args, kwargs);
+    if (!res) throw std::runtime_error("Call to set_aspect() failed.");
+    Py_DECREF(set_aspect);
+
+    Py_DECREF(ax);
+    Py_DECREF(args);
+    Py_DECREF(kwargs);
+}
+
 template<typename Numeric>
 void ylim(Numeric left, Numeric right)
 {