The Docs

matplotlibcpp namespace

All functions are organised in the namespace matplotlibcpp. For convenience (and in spirit of the Python norm) we usually define 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 with a generic vector type where possible. All template types named Vector* 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 with another 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 = {})
_images/matplotlib_icon.png

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 the line. 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 supported
plt::legend();
template<typename VectorY>
bool plot(const VectorY &y, const std::string &format = "", const std::map<std::string, std::string> &keywords = {})
_images/matplotlib_icon.png

Plot y.

For a vector \(y\) of size \(n\), the \(x\) data is set to \({0, ..., n - 1}\). The formatting string s can specify the colour, markers and style of the line. 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 = {})
_images/matplotlib_icon.png

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 = {})
_images/matplotlib_icon.png

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 namespace definition 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 = {})
_images/matplotlib_icon.png

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 = {})
_images/matplotlib_icon.png

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 = {})
_images/matplotlib_icon.png

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 = {})
_images/matplotlib_icon.png

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 = "")
_images/matplotlib_icon.png

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)
_images/matplotlib_icon.png

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)
_images/matplotlib_icon.png

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())
_images/matplotlib_icon.png

Enable the figure legend.

Template Parameters:
 

Vector – vector-like type, see Vector, defaults to 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 it specifies 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 the plot axes (thus no normalised coordinates)

Example

// Put the legend in the center of the bottom right quadrant.
// First argument: loc, second: bbox_to_anchor
plt::legend("center", {0.5, 0, 0.5, 0.5});
template<typename Numeric>
void xlim(Numeric left, Numeric right)
_images/matplotlib_icon.png

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)
_images/matplotlib_icon.png

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 = {})
_images/matplotlib_icon.png

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 = {})
_images/matplotlib_icon.png

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)
_images/matplotlib_icon.png

Set some axis properties.

Parameters:option – The option to activate
option Result
on Turn on axis lines and labels
off Turn off axis lines and labels
equal Set equal scaling (i.e., make circles circular) by changing axis limits.
scaled Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box.
tight Set limits just large enough to show all data.
auto Automatic scaling (fill plot box with data).
image scaled with axis limits equal to data limits.
square Square 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 = {})
_images/matplotlib_icon.png

Save the current figure.

Supported file types depend on the user backend, but usually contain 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_sales
plt::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 empty

plt::plot(x, y);
plt::savefig("this_isnt_empty.pdf");  // always call savefig *before* show
plt::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)
_images/matplotlib_icon.png

Display the figure.

Parameters:block – If true, the execution of the code is stopped until the displayed figure is closed. Otherwise the code is not stopped. Depending on the backend, figures might not get displayed at all.