Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
98 строки
2.8 KiB
C++
98 строки
2.8 KiB
C++
#include <iostream>
|
|
#include <vector>
|
|
#include <string>
|
|
#include <algorithm>
|
|
#include "svg.h"
|
|
|
|
using namespace std;
|
|
|
|
void svg_begin(double width, double height) {
|
|
cout << "<?xml version='1.0' encoding='UTF-8'?>\n";
|
|
cout << "<svg ";
|
|
cout << "width='" << width << "' ";
|
|
cout << "height='" << height << "' ";
|
|
cout << "viewBox='0 0 " << width << " " << height << "' ";
|
|
cout << "xmlns='http://www.w3.org/2000/svg'>\n";
|
|
}
|
|
|
|
void svg_end() {
|
|
cout << "</svg>\n";
|
|
}
|
|
|
|
void svg_text(double left, double baseline, const string& text) {
|
|
cout << "<text x='" << left << "' y='" << baseline << "' "
|
|
<< "font-family='Arial' font-size='12' "
|
|
<< "text-anchor='end' dominant-baseline='middle'>"
|
|
<< text << "</text>\n";
|
|
}
|
|
|
|
void svg_rect(double x, double y, double width, double height,
|
|
string stroke, string fill) {
|
|
cout << "<rect x='" << x << "' y='" << y << "' width='" << width
|
|
<< "' height='" << height << "' stroke='" << stroke
|
|
<< "' fill='" << fill << "' stroke-width='1' />\n";
|
|
}
|
|
|
|
void show_histogram_svg(const vector<size_t>& bins) {
|
|
const auto IMAGE_WIDTH = 400;
|
|
const auto TEXT_LEFT = 20;
|
|
const auto TEXT_BASELINE = 15;
|
|
const auto TEXT_WIDTH = 50;
|
|
const auto BIN_HEIGHT = 30;
|
|
const auto MARGIN = 10;
|
|
|
|
// Àâòîìàòè÷åñêè ðàññ÷èòûâàåì âûñîòó èçîáðàæåíèÿ
|
|
const auto IMAGE_HEIGHT = bins.size() * BIN_HEIGHT + 2 * MARGIN;
|
|
|
|
svg_begin(IMAGE_WIDTH, IMAGE_HEIGHT);
|
|
|
|
// Íàõîäèì ìàêñèìàëüíîå çíà÷åíèå äëÿ ìàñøòàáèðîâàíèÿ
|
|
size_t max_count = 0;
|
|
for (size_t count : bins) {
|
|
if (count > max_count) {
|
|
max_count = count;
|
|
}
|
|
}
|
|
|
|
// Ìàñøòàáèðóåì øèðèíó ñòîëáöîâ
|
|
const double max_width = IMAGE_WIDTH - TEXT_WIDTH - MARGIN;
|
|
|
|
double top = MARGIN;
|
|
for (size_t i = 0; i < bins.size(); i++) {
|
|
size_t bin = bins[i];
|
|
|
|
// Ìàñøòàáèðóåì øèðèíó ñòîëáöà
|
|
double bin_width = 0;
|
|
if (max_count > 0) {
|
|
bin_width = (static_cast<double>(bin) / max_count) * max_width;
|
|
}
|
|
|
|
// Âûâîäèì ïîäïèñü
|
|
svg_text(TEXT_LEFT, top + BIN_HEIGHT / 2, to_string(bin));
|
|
|
|
// Âûáèðàåì öâåò â çàâèñèìîñòè îò çíà÷åíèÿ
|
|
string fill_color;
|
|
if (max_count > 0) {
|
|
double ratio = static_cast<double>(bin) / max_count;
|
|
if (ratio > 0.8) {
|
|
fill_color = "#ff4444";
|
|
} else if (ratio > 0.5) {
|
|
fill_color = "#ffaa44";
|
|
} else if (ratio > 0.2) {
|
|
fill_color = "#44ff44";
|
|
} else {
|
|
fill_color = "#4444ff";
|
|
}
|
|
} else {
|
|
fill_color = "#888888";
|
|
}
|
|
|
|
// Âûâîäèì ñòîëáåö
|
|
svg_rect(TEXT_WIDTH, top, bin_width, BIN_HEIGHT, "#333333", fill_color);
|
|
|
|
top += BIN_HEIGHT;
|
|
}
|
|
|
|
svg_end();
|
|
}
|