- Docs »
- The Docs
- Edit on GitHub
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.
- typedef double
Plot commands¶
- template<typename
VectorX
, typenameVectorY
>
boolplot
(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ Plot y versus x.
See Alsomatplotlib.pyplot.plot — Matplotlib 3.9.2 documentationPython Plotting With Matplotlib (Guide) – Real Pythonmatplotlib.pyplot.scatter — Matplotlib 3.9.2 documentationmatplotlib.pyplot.colorbar — Matplotlib 3.9.2 documentationThe 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
>
boolplot
(const VectorY &y, const std::string &format = "", const std::map<std::string, std::string> &keywords = {})¶ 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
, typenameVectorY
>
boolloglog
(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ 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
>
boolloglog
(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ 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
andmatplotlibcpp
import and the namespacedefinitionplt = 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
, typenameVectorY
>
boolsemilogx
(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ 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
>
boolsemilogx
(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ 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
, typenameVectorY
>
boolsemilogy
(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ 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
>
boolsemilogy
(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})¶ 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
>
voidtext
(Numeric x, Numeric y, const std::string &s = "")¶ 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)¶ 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)¶ 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 voidlegend
(const std::string &loc = "best", const Vector &bbox_to_anchor = Vector())¶ 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
>
voidxlim
(Numeric left, Numeric right)¶ 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
>
voidylim
(Numeric bottom, Numeric top)¶ 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 = {})¶ 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 = {})¶ 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)¶ 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 = {})¶ 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"}});