lava / matplotlib-cpp

Extremely simple yet powerful header-only C++ plotting library built on the popular matplotlib
MIT License
4.45k stars 1.15k forks source link

3D Scatter Plot animation #306

Open Sean340927 opened 2 years ago

Sean340927 commented 2 years ago

Hi Is there a way to update the data in a 3D scatter plot in order to produce an animation? (My intention is to plot 3D data in real time). I have checked both the animation.cpp and update.cpp examples, but had no luck. Any help would be appreciated. Many thanks.

Hummel-Wang commented 2 years ago

Hi
Have you found a solution? if have, Can you share with me...

jmz3 commented 1 year ago

Hi, I figured out a way to solve this problem. To make an animation of the 3d plot, you have to specify the figure handle. The header get it done by default for the 2d plot, but not for 3d. So here is a possible way for doing this:

#include "matplotlibcpp.h"
#include <vector>
#include <map>
#include <cmath>

namespace plt = matplotlibcpp;
using namespace std;
const long fg = plt::figure(); // Define the figure handle number here

int main()
{
    std::map<std::string, std::string> kwargs;
    kwargs["marker"] = "o";
    kwargs["linestyle"] = "-";
    kwargs["linewidth"] = "1";
    kwargs["markersize"] = "12";
    vector<double> x, y, z;
    x = {1, 2, 3, 4};
    y = {1, 2, 2, 1};
    z = {1, 2, 3, 4};

    int loop_num = 0;
    while (loop_num <= 50)
    {
        for (int j = 0; j < x.size(); j++)
        {
            x[j] = x[j] + cos(2 * M_PI / (loop_num + 1));
        }
        plt::plot3(x, y, z, kwargs, fg); // Specify the number of the figure
        plt::xlim(0.0, 10.0);
        plt::ylim(0.0, 10.0);
        plt::pause(0.05);
        plt::clf();
        // plt::close();
        loop_num++;
    }

    return 0;
}