#include "svg.h" #include <algorithm> #include <string> using namespace std; namespace svg { void begin(ostream& out, double width, double height) { out << "<?xml version='1.0' encoding='UTF-8'?>\n"; out << "<svg width='" << width << "' height='" << height << "' " << "viewBox='0 0 " << width << " " << height << "' " << "xmlns='http://www.w3.org/2000/svg'>\n"; } void end(ostream& out) { out << "</svg>\n"; } void text(ostream& out, double left, double baseline, const string& text) { out << "<text x='" << left << "' y='" << baseline << "'>" << text << "</text>\n"; } void rect(ostream& out, double x, double y, double width, double height, const string& stroke, const string& fill) { out << "<rect x='" << x << "' y='" << y << "' width='" << width << "' height='" << height << "' stroke='" << stroke << "' fill='" << fill << "' />\n"; } void show_histogram_svg(ostream& out, const vector<size_t>& bins) { begin(out, IMAGE_WIDTH, IMAGE_HEIGHT); if (bins.empty()) { end(out); return; } size_t max_count = *max_element(bins.begin(), bins.end()); double scale = (max_count > 0) ? (IMAGE_WIDTH - TEXT_WIDTH) / static_cast<double>(max_count) : 1.0; double top = 0; for (size_t bin : bins) { const double bin_width = bin * scale; text(out, TEXT_LEFT, top + TEXT_BASELINE, to_string(bin)); string fill_color = (static_cast<int>(top / BIN_HEIGHT) % 2 == 0) ? "#aaffaa" : "#aaaaff"; rect(out, TEXT_WIDTH, top, bin_width, BIN_HEIGHT, "black", fill_color); top += BIN_HEIGHT; } end(out); } }