This gallery example demonstrates creating an interactive correlation matrix heatmap using Plotly.cpp. It generates realistic business performance data across multiple metrics and displays their correlations using color coding and text annotations.
The visualization helps identify relationships between different business metrics such as revenue, profit, marketing spend, and customer satisfaction.
#include <array>
#include <cmath>
#include <cstdio>
#include <random>
#include <string>
#include <vector>
auto main(
int argc,
char *argv[]) ->
int {
std::vector<std::string> variables = {"Revenue", "Profit",
"Marketing", "R&D",
"Employees", "Customer_Satisfaction",
"Market_Share"};
const size_t n = variables.size();
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> correlationDist(-0.8, 0.9);
std::vector<std::vector<double>> correlationMatrix(n, std::vector<double>(n));
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
if (i == j) {
correlationMatrix[i][j] = 1.0;
} else if (i < j) {
double corr = correlationDist(gen);
if ((variables[i] == "Revenue" && variables[j] == "Profit") ||
(variables[i] == "Marketing" && variables[j] == "Market_Share") ||
(variables[i] == "R&D" &&
variables[j] == "Customer_Satisfaction")) {
corr = std::abs(corr) * 0.8 + 0.2;
}
correlationMatrix[i][j] = corr;
correlationMatrix[j][i] = corr;
}
}
}
std::vector<std::vector<std::string>> textMatrix(n,
std::vector<std::string>(n));
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
std::array<char, 10> buffer;
std::snprintf(buffer.data(), buffer.size(), "%.2f",
correlationMatrix[i][j]);
textMatrix[i][j] = buffer.data();
}
}
{"type", "heatmap"},
{"x", variables},
{"y", variables},
{"z", correlationMatrix},
{"text", textMatrix},
{"texttemplate", "%{text}"},
{"textfont", {{"size", 12}, {"color", "white"}}},
{"colorscale", "RdBu"},
{"zmid", 0.0},
{"showscale", true},
{"colorbar",
{{"title", "Correlation Coefficient"}, {"titleside", "right"}}}};
{"title",
{{"text", "Business Metrics Correlation Matrix"},
{"font", {{"size", 16}}}}},
{"xaxis",
{{"title", "Variables"}, {"side", "bottom"}, {"tickangle", 45}}},
{"yaxis",
{
{"title", "Variables"}, {"autorange", "reversed"}
}},
{"width", 800},
{"height", 700},
{"margin", {{"l", 150}, {"r", 100}, {"t", 100}, {"b", 150}}}};
std::vector<plotly::Object> data = {trace};
if (!args.headless) {
} else {
{"width", 800},
{"height", 700},
{"filename", "heatmap_correlation"}};
}
return 0;
}
auto parseGalleryArgs(int argc, char *argv[]) -> GalleryArgs
Parse command line arguments for gallery examples.
Definition arg_parser.cpp:4
auto main() -> int
Definition gallery_animate_sin_wave.cpp:48
nlohmann::json Object
Definition plotly.hpp:26
Public Plotly C++ API header.