Monday, May 6, 2024

Install, Link and Run Matplotlib in C++ (Linux)

Matplotlib is the famous library in python to plot and visualize data of different types. In this article we will see how we can use this powerful tool in C++.

Step 1 : Install some important libraries

Matplotlib for C++ requires a working Python installation as well as Matplotlib. Python2.7 and Python3 (>= 3.6) have been tested, but other versions should work as well. In the linking process the exact version of Python to use can be specified by linking the according library.

 $ cd Downloads
 $ sudo apt-get install python3.8-dev
 $ sudo apt-get install python3.8-numpy
 $ sudo apt-get install python3-matplotlib
 $ wget https://raw.githubusercontent.com/lava/matplotlib-cpp/master/matplotlibcpp.h

In a download directory a file is downloaded named ‘matplotlibcpp.h’. This files is the C++ wrapper of matplotlib python. Save this file and store it in the include directory of your project. Later we link this file or library with our main program using G++ or CMAKELISTS.

Step 2 : Write a main program

Create a file main.cpp in the src folder of your project. Write some program to test this matplolib library in C++.

 #include "matplotlibcpp.h"
 namespace plt = matplotlibcpp;
 int main()
 {
  plt::plot({1,2,3,4}, "*");
  plt::show();
  plt::detail::_interpreter::kill();
  return 0;
 }

Step 3 : Link Matplotlib library with main program and Run

There are two ways you can link your libraries with your program. The first one is by using the g++ compiler and the other one is using the Cmake method.

Step 3.1 : G++

By using a G++ complier type this command in the shell:

$ g++ src/main.cpp -o result_plot -I /usr/include/python3.8 -I include/ -lpython3.8

The matplotlib depends on the python.h, numpy and libpython. So -I /usr/include/python3.8 is used to compiler where to look and link the python.h library to the main program and -lpython3.8 is used to link the libpython to your main program. After using this command an executable file is generated for your main program named result_plot which contains the ouput of your main program. To run this file type the following command in your terminal.

$ ./result_plot

How to Auto Remove Silent Audio Segments with Python

Robotics Workshop 4 min read · Nov 4, 2024 In this article, I’ll show you how to find silent and non-silent parts in your audio or vide...