Skip to content

Function Plot

1
fplot(fx);

example_fplot_1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <cmath>
#include <matplot/matplot.h>

int main() {
    using namespace matplot;

    fplot("cos(x)", "o-r")->line_width(2);
    hold(on);
    fplot([](double x) { return sin(x); }, std::array<double, 2>{-10, 10},
          "x--b")
        ->line_width(2);

    show();
    return 0;
}

More examples

example_fplot_2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <cmath>
#include <matplot/matplot.h>

int main() {
    using namespace matplot;

    fplot([](double t) { return cos(3 * t); },
          [](double t) { return sin(2 * t); });

    show();
    return 0;
}

example_fplot_3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <cmath>
#include <matplot/matplot.h>

int main() {
    using namespace matplot;

    fplot([](double x) { return exp(x); }, std::array<double, 2>{-3, 0}, "b");
    hold(on);
    fplot([](double x) { return cos(x); }, std::array<double, 2>{0, 3}, "b");
    hold(off);
    grid(on);

    show();
    return 0;
}

example_fplot_4

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <cmath>
#include <matplot/matplot.h>

int main() {
    using namespace matplot;

    auto f = fplot([](double x) { return sin(x + pi / 5); });
    f->line_width(2);
    hold(on);
    fplot([](double x) { return sin(x - pi / 5); }, "--or");
    fplot([](double x) { return sin(x); }, "-.*c");
    hold(off);

    show();
    return 0;
}

example_fplot_5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <cmath>
#include <matplot/matplot.h>

int main() {
    using namespace matplot;

    auto fp = fplot([](double x) { return sin(x); });
    fp->line_style(":");
    fp->color("r");
    fp->marker("x");
    fp->marker_color("b");

    show();
    return 0;
}

example_fplot_6

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cmath>
#include <matplot/matplot.h>

int main() {
    using namespace matplot;

    fplot([](double x) { return sin(x); },
          std::array<double, 2>{-2 * pi, 2 * pi});
    grid(on);
    title("sin(x) from -2π to 2π");
    xlabel("x");
    ylabel("y");

    auto ax = gca();
    ax->x_axis().tick_values(iota(-2 * pi, pi / 2, 2 * pi));
    ax->x_axis().ticklabels(
        {"-2π", "-3π/2", "-π", "-π/2", "0", "π/2", "π", "3π/2", "2π"});

    show();
    return 0;
}

Instead of storing data points, the objects function line and string function store a function as a lambda function or as a string with an expression. These objects use lazy evaluation to generate absolute data points. The data is generated only when the draw function is called.