Skip to content

Instantly share code, notes, and snippets.

@EMPAT94
Last active September 22, 2020 06:14
Show Gist options
  • Save EMPAT94/818b0b5e41e4c37b30d3407d6247ca52 to your computer and use it in GitHub Desktop.
Save EMPAT94/818b0b5e41e4c37b30d3407d6247ca52 to your computer and use it in GitHub Desktop.
Hasty Charts
/**
* This is a quick and dirty way to make charts in HTML.
*
* I made this for an email campaign, where embedding images was cumbersome
*/
function chart({ x_axis_values, x_axis_label, y_axis_values, y_axis_unit }) {
const x_axis = x_axis_values
.map(d => `<td style="text-align:center;vertical-align:top;font-size:8px;">${d}</td>`)
.join("\n");
const max = parseFloat(y_axis_values.reduce((a, v) => (+a > +v ? +a : +v), 0));
const decimals = max < 10 ? 2 : 0;
const bars = y_axis_values
.map(
d =>
`<td style="vertical-align:bottom;"><div style="width:100%;height: ${(d / max) * 100}%; background-color: rgba(255,165,0,0.84);"></div></td>`
)
.join("\n");
return `<table
style="width: 600px; height: 300px;"
cellspacing="0"
cellpadding="0"
>
<tr>
<td style="width: 10%;">
<table style="height: 100%; width: 100%; text-align: end;" cellpadding="1">
<tr style="width: 100%; height: 10%;">
<td style="font-size:10px;vertical-align:top;">${max.toFixed(decimals) + y_axis_unit}</td>
</tr>
<tr style="width: 100%; height: 10%">
<td style="font-size:10px;vertical-align:top;">${(0.75 * max).toFixed(decimals) + y_axis_unit}</td>
</tr>
<tr style="width: 100%; height: 10%">
<td style="font-size:10px;vertical-align:top;">${(0.5 * max).toFixed(decimals) + y_axis_unit}</td>
</tr>
<tr style="width: 100%; height: 10%">
<td style="font-size:10px;vertical-align:top;">${(0.25 * max).toFixed(decimals) + y_axis_unit}</td>
</tr>
</table>
</td>
<td style="width: 90%;">
<table style="
width: 100%;
height: 90%;
table-layout: fixed;
border-left: 1px solid #4a4a4a;
border-bottom: 1px solid #4a4a4a;"
cellpadding="0">
<tr>
${bars}
</tr>
</table>
<table style="width: 100%; height: 5%; table-layout: fixed;" cellpadding="0">
<tr>
${x_axis}
</tr>
</table>
<table style="width: 100%; height: 5%;" cellpadding="0">
<tr><td align="center" style="color: #4a4a4a;"> ${x_axis_label} </td></tr>
</table>
</td>
</tr>
</table>
`;
}
// --------------- USAGE --------------- //
const { writeFileSync } = require("fs");
function example() {
console.log("Running example");
const chart_html = chart({
x_axis_values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
x_axis_label: "x axis",
y_axis_values: [100, 70, 80, 90, 100, 60, 70, 80, 90, 100],
y_axis_unit: " unit"
});
writeFileSync("./chart.html", chart_html);
}
example();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment