This example demonstrates real-time animation capabilities using Plotly's frame-based animation system to visualize a phase-shifting sine wave with smooth transitions and interactive playback controls.
The example creates a continuously animated sine wave that shifts phase over time:
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
std::cout << "Starting animated sin wave with animate function..." << '\n';
const double xMin = -4 * M_PI;
const double xMax = 4 * M_PI;
const int numPoints = 400;
const int numFrames = 60;
const double phaseStep = 0.2;
auto x =
linspace(xMin, xMax, numPoints);
std::vector<double> yInitial;
yInitial.reserve(x.size());
for (const auto &xi : x) {
yInitial.push_back(std::sin(xi));
}
{"y", yInitial},
{"type", "scatter"},
{"mode", "lines"},
{"line", {{"color", "blue"}, {"width", 3}}},
{"name", "sin(x + φ)"}};
{"title", {{"text", "Animated Sin Wave - Using animate() function"}}},
{"xaxis",
{{"title", "x"},
{"range", std::vector<double>{xMin, xMax}},
{"showgrid", true}}},
{"yaxis",
{{"title", "sin(x + φ)"},
{"range", std::vector<double>{-1.5, 1.5}},
{"showgrid", true}}},
{"showlegend", true},
{"width", 800},
{"height", 600},
{"updatemenus",
std::vector<plotly::Object>{
{{"type", "buttons"},
{"direction", "left"},
{"showactive", false},
{"x", 0.1},
{"y", 0},
{"xanchor", "right"},
{"yanchor", "top"},
{"buttons",
std::vector<plotly::Object>{
{{"label", "Play"},
{"method", "animate"},
{"args",
std::vector<plotly::Object>{
{{"frame", {{"duration", 100}, {"redraw", false}}},
{"transition", {{"duration", 0}}},
{"fromcurrent", true},
{"mode", "immediate"}}}}},
{{"label", "Pause"},
{"method", "animate"},
{"args",
std::vector<plotly::Object>{
std::vector<plotly::Object>(),
{{"frame", {{"duration", 0}, {"redraw", false}}},
{"transition", {{"duration", 0}}},
{"mode", "immediate"}}}}}}}}}}};
std::vector<plotly::Object> data = {initialTrace};
std::vector<plotly::Object> frames;
frames.reserve(numFrames);
for (int frame = 0; frame < numFrames; frame++) {
double phase = frame * phaseStep;
std::vector<double> yFrame;
yFrame.reserve(x.size());
for (const auto &xi : x) {
yFrame.push_back(std::sin(xi + phase));
}
{"name", std::to_string(frame)},
{"data", std::vector<plotly::Object>{
{{"x", x}, {"y", yFrame}, {"type", "scatter"}}}}};
frames.push_back(frameObj);
}
std::cout << "Adding " << frames.size() << " animation frames..." << '\n';
std::cout << "Starting animation. Use the Play/Pause buttons to control."
<< '\n';
{"frame", {{"duration", 100}, {"redraw", false}}},
{"transition", {{"duration", 50}}},
{"fromcurrent", true},
{"mode", "immediate"}};
return 0;
}
auto main() -> int
Definition gallery_animate_sin_wave.cpp:48
auto linspace(double a, double b, int n) -> std::vector< double >
Create a linearly spaced vector of values between two endpoints.
Definition linspace.cpp:4
nlohmann::json Object
Definition plotly.hpp:26
Public Plotly C++ API header.