Program Listing for File scatter.h

Return to documentation for file (source/plot_types/scatter.h)

/*
 * scatter.h ScatterPlot data class
 *
 * Author:              Tom Clark  (thclark@github)
 *
 * Copyright (c) 2017-9 T Clark. All Rights Reserved.
 *
 */

#ifndef CPPLOT_SCATTER_H
#define CPPLOT_SCATTER_H

#include <vector>
#include <string.h>
#include <Eigen/Dense>
#include <nlohmann/json.hpp>

#include "eigen.h"
#include "exceptions.h"


namespace cpplot {


class Line {
public:
    // Allow the serialiser function to access protected members
    friend void to_json(nlohmann::json& j, const Line& p);

    Line() {
        is_empty = true;
        width = -1; // This is "empty" i.e. not set.
    }

    void setColor(const std::string &value) {
        color = value;
        is_empty = false;
    }

    void setDash(const std::string &value) {
        // TODO check the string is valid, or enumerate.
        dash = value;
        is_empty = false;
    }

    void setWidth(const int value) {
        width = value;
        is_empty = false;
    }

    bool empty() const {
        return is_empty;
    }

protected:
    std::string dash;
    int width;
    std::string color;
    bool is_empty;

};


void to_json(nlohmann::json& j, const Line& p) {
    if (!p.dash.empty()) {
        j["dash"] = p.dash;
    };
    if (p.width != -1) {
        j["width"] = p.width;
    };
    if (!p.color.empty()) {
        j["color"] = p.color;
    }
}


class ScatterPlot {
public:
    // Allow the serialiser function to access protected members
    friend void to_json(nlohmann::json& j, const ScatterPlot& p);

    // TODO move to getter/setters
    Eigen::VectorXd x;
    Eigen::VectorXd y;
    std::string name = "";

    ScatterPlot() {
        x = Eigen::VectorXd::LinSpaced(3, 0.0, 2.0);
        y = Eigen::VectorXd::LinSpaced(3, 1.0, 3.0);
        line = Line();
    }

    void setColor(const std::string &value) {
        line.setColor(value);
    }

    void setDash(const std::string &value) {
        line.setDash(value);
    }

    void setWidth(const int value) {
        line.setWidth(value);
    }

protected:
    Line line;

};


void to_json(nlohmann::json& j, const ScatterPlot& p) {

    nlohmann::json x;
    nlohmann::json y;
    to_json(x, p.x);
    to_json(y, p.y);
    j["x"] = x;
    j["y"] = y;
    j["type"] = "scatter";
    if (!p.name.empty()) {
        j["name"] = p.name;
    }
    if (!p.line.empty()) {
        nlohmann::json line;
        to_json(line, p.line);
        j["line"] = line;
    }
};


} // end namespace

#endif //CPPLOT_SCATTER_H