The Docs — Matplotlib for C++ documentation (2024)

matplotlibcpp namespace

All functions are organised in the namespace matplotlibcpp.For convenience (and in spirit of the Python norm) we usuallydefine the abbreviation plt:

#include "matplotlibcpp.h"namespace plt = matplotlibcpp;

The function can then be accessed via:

matplotlibcpp::plot(x, y);plt::loglog(x, y); // if we defined namespace plt = matplotlibcpp

Vector type

type Vector

Functions in the Matplotlib-C++ library are designed to work witha generic vector type where possible. All template types namedVector* must support the following operations.See the STL vector documentation for more detail on the implementation.

Note

Check the declarations with the STL doc

typedef double value_type

Definition of the underlying type, double may be replaced withanother suitable type.

std::size_t size()

Return the size of the vector.

value_type operator[](const std::size_t i)
value_type at(const std::size_t i)

Return the i th element of the vector.

value_type *data()

Return a pointer to the first element of the data in the vector.The data must furthermore be stored in a consecutive manner.

value_type *begin()

Return a pointer to the first element of the data in the vector.

value_type *end()

Return a pointer directly behind the last element of the data in the vector.

Plot commands

template<typename VectorX, typename VectorY>
bool plot(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (1)

Plot y versus x.

The two vectors \(x\) and \(y\) must have the same length.The formatting string s can specify the colour, markers and style of theline.The map keywords may contain additional named arguments for the plot.

Template Parameters:
  • VectorX – vector-like type, see Vector
  • VectorY – vector-like type, see Vector
Parameters:
  • x\(x\) data for the plot
  • y\(y\) data for the plot
  • s – (optional) formatting string, see here
  • keywords – (optional) map specifying additional keywords, see here
Returns:

true if no error has occured, false otherwise

Minimal working example

#include <vector>#include "matplotlibcpp.h"namespace plt = matplotlibcpp;int main() { std::vector<double> x = {1, 2, 3, 4}; std::vector<double> y = {1, 4, 9, 16}; plt::plot(x, y); plt::show(); return 0;}

Example with formatting strings

plt::plot(x, y, "r*"); // Red stars as markers, no line
plt::plot(x, y, "bo-"); // Blue dots + blue line

Example with keywords

plt::plot(x, y, "bo-", {{"label", "f(x)"}}); // add the label f(x)plt::legend(); // remember to activate the legend
plt::plot(x, y, {{"label", "$y = x^2$"}}); // latex is supportedplt::legend();
template<typename VectorY>
bool plot(const VectorY &y, const std::string &format = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (2)

Plot y.

For a vector \(y\) of size \(n\), the \(x\) datais set to \({0, ..., n - 1}\).The formatting string s can specify the colour, markers and style of theline.The map keywords may contain additional named arguments for the plot.

Template Parameters:

VectorY – vector-like type, see Vector

Parameters:
  • y\(y\) data for the plot
  • s – (optional) formatting string, see here
  • keywords – (optional) map specifying additional keywords, see here
Returns:

true if no error has occured, false otherwise

Examples

#include <vector>#include "matplotlibcpp.h"namespace plt = matplotlibcpp;int main() { std::vector<int> y = {1, 2, 3}; plt::plot(y, "bo-"); plt::show(); return 0;}
Eigen::VectorXd y = {1, 2, 3};plt::plot(y, {{"label", "1 to 3"}});plt::show();
template<typename VectorX, typename VectorY>
bool loglog(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (3)

Plot y versus x in double logarithmic scale.

See plot() for explanation of the parameters.

Note

All following plots will be in double logarithmic scale,also calls to plot.

Example

#include <Eigen/Dense>#include "matplotlibcpp.h"namespace plt = matplotlibcpp;int main() { int n = 5000; Eigen::VectorXd x(n), y(n), z(n), w = Eigen::VectorXd::Ones(n); for (int i = 0; i < n; ++i) { double value = (1.0 + i) / n; x(i) = value; y(i) = value * value; z(i) = value * value * value; } plt::loglog(x, y); // f(x) = x^2 plt::loglog(x, w, "r--"); // f(x) = 1, red dashed line plt::loglog(x, z, "g:", {{"label", "$x^3$"}}); // f(x) = x^3, green dots + label plt::title("Some functions of $x$"); // add a title plt::show();}
template<typename VectorY>
bool loglog(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (4)

Plot y in double logarithmic scale.

See plot() for explanation of the parameters.

Note

All following plots will be in double logarithmic scale,also calls to plot.

Examples

Assuming vector and matplotlibcpp import and the namespacedefinition plt = matplotlibcpp.

std::vector<int> y = {1, 10, 100, 1000};plt::loglog(y);
std::vector<double> y1 = {1, 2, 4}, y2 = {1, 3, 9};plt::loglog(y, "bo-", {{"label", "powers of 2"}});plt::plot(y, "ro-", {{"label", "powers of 3"}}); // also in loglog scale
template<typename VectorX, typename VectorY>
bool semilogx(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (5)

Plot y versus x in logarithmic x and linear y scale.

See plot() for explanation of the parameters.

Note

All following plots will inherit the logarithmic x scale,also calls to plot.

template<typename VectorY>
bool semilogx(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (6)

Plot y in logarithmic x and linear y scale.

See plot() for explanation of the parameters.

Note

All following plots will inherit the logarithmic x scale,also calls to plot.

template<typename VectorX, typename VectorY>
bool semilogy(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (7)

Plot y versus x in linear x and logarithmic y scale.

See plot() for explanation of the parameters.

Note

All following plots will inherit the logarithmic y scale,also calls to plot.

template<typename VectorY>
bool semilogy(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (8)

Plot y in linear x and logarithmic y scale.

See plot() for explanation of the parameters.

Note

All following plots will inherit the logarithmic y scale,also calls to plot.

template<typename Numeric>
void text(Numeric x, Numeric y, const std::string &s = "")
The Docs — Matplotlib for C++ documentation (9)

Place text at location \((x,y)\).

Template Parameters:

Numeric – A scalar-like type

Parameters:
  • x – The \(x\) location of the text
  • y – The \(y\) location of the text
  • s – The text to be placed in the plot

Example

#include <vector>#include "matplotlibcpp.h"namespace plt = matplotlibcpp;int main() { std::vector<double> x = {0.1, 0.2, 0.5}; plt::plot(x, "s"); plt::text(1.0, 0.1, "Text under a square"); plt::show(); return 0;}

Figure commands

inline long figure(long number = -1)
The Docs — Matplotlib for C++ documentation (10)

Initialise a new figure with the ID number.

Parameters:number – The number of the figure. If set to -1 default numbering(increasing from 0 on) is used
Returns:The number of the figure
inline bool fignum_exists(long number)
The Docs — Matplotlib for C++ documentation (11)

Check if a figure of given number exists.

Parameters:number – The number of the figure
Returns:true, if a figure with given number exists, false otherwise
inline void figure_size(size_t w, size_t h)

Call plt::figure() and set the figure size to w x h pixels.

Parameters:
  • w – The width of the figure in pixels
  • h – The height of the figure in pixels
template<typename Vector = std::vector<double>>
inline void legend(const std::string &loc = "best", const Vector &bbox_to_anchor = Vector())
The Docs — Matplotlib for C++ documentation (12)

Enable the figure legend.

Template Parameters:

Vector – vector-like type, see Vector, defaultsto std::vector<double>

Parameters:
  • loc – The location of the legend. May be any of:“best”, “upper left”, “upper center”, “upper left”,“center left”, “center”, “center right” (= “right”),“lower left”, “lower center”, “lower right”
  • bbox_to_anchor – If set to a vector of length 2 or 4 itspecifies the location (and size) of the legend’s bounding box.Format is (x, y) or (x, y, width, height).The coordinates are interpreted in the same units as theplot axes (thus no normalised coordinates)

Example

// Put the legend in the center of the bottom right quadrant.// First argument: loc, second: bbox_to_anchorplt::legend("center", {0.5, 0, 0.5, 0.5});
template<typename Numeric>
void xlim(Numeric left, Numeric right)
The Docs — Matplotlib for C++ documentation (13)

Set the x axis limits.

Template Parameters:

Numeric – A scalar-like type

Parameters:
  • left – The left axis limit
  • right – The right axis limit
template<typename Numeric>
void ylim(Numeric bottom, Numeric top)
The Docs — Matplotlib for C++ documentation (14)

Set the y axis limits.

Template Parameters:

Numeric – A scalar-like type

Parameters:
  • bottom – The bottom axis limit
  • top – The top axis limit
inline double *xlim()

Get the x axis limits.

Returns:A pointer to an array of length 2 containing [left, right]
inline double *ylim()

Get the y axis limits.

Returns:A pointer to an array of length 2 containing [bottom, top]
inline void title(const std::string &titlestr, const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (15)

Set the title of the plot.

Parameters:
  • titlestr – Title of the plot
  • keywords – Additional keywords, see here for a list
inline void suptitle(const std::string &suptitlestr, const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (16)

Add a centered title to the figure.

Parameters:
  • suptitlestr – Title of the figure
  • keywords – Additional keywords, see here for a list
inline void axis(const std::string &option)
The Docs — Matplotlib for C++ documentation (17)

Set some axis properties.

Parameters:option – The option to activate
optionResult
onTurn on axis lines and labels
offTurn off axis lines and labels
equalSet equal scaling (i.e., make circles circular) by changing axis limits.
scaledSet equal scaling (i.e., make circles circular) by changing dimensions of the plot box.
tightSet limits just large enough to show all data.
autoAutomatic scaling (fill plot box with data).
imagescaled with axis limits equal to data limits.
squareSquare plot; similar to scaled, but initially forcing same x- and y-axis length.
inline void savefig(const std::string &filename, const std::map<std::string, std::string> &keywords = {})
The Docs — Matplotlib for C++ documentation (18)

Save the current figure.

Supported file types depend on the user backend, but usuallycontain pdf, eps and png. To find all supported formats try

$ python3>>> import matplotlib.pyplot as plt>>> plt.gcf().canvas.get_supported_filetypes_grouped()
Parameters:
  • filename – Save the figure to filename (must contain file format)
  • keywords – Additional keywords, see Other Parameters here for a complete list

Examples

plt::plot(x, y);plt::savefig("plot.pdf");

Always the current state of the figure is stored.

plt::plot(time, apple_sales);plt::savefig("sales.pdf"); // contains only apple_salesplt::plot(time, kiwi_sales);plt::savefig("sales.pdf"); // contains apple and kiwi sales

Calling plt::show() clears the plot!

plt::plot(x, y);plt::show();plt::savefig("is_this_empty.pdf"); // yes, this will be emptyplt::plot(x, y);plt::savefig("this_isnt_empty.pdf"); // always call savefig *before* showplt::show();

Optimally use the available canvas space with {{“bbox_inches”, “tight”}}.This can be useful if e.g. the axis labels are too far outside and get cut off.

plt::savefig("fig.pdf", {{"bbox_inches", "tight"}});
inline void show(const bool block = true)
The Docs — Matplotlib for C++ documentation (19)

Display the figure.

Parameters:block – If true, the execution of the code is stopped until thedisplayed figure is closed. Otherwise the code is not stopped.Depending on the backend, figures might not get displayedat all.
The Docs — Matplotlib for C++  documentation (2024)
Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 6513

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.