Skrip Aneka Ragam Grafik
Ditulis ulang Oleh: Alfians Increms April, 2022
Aplikasi: Perkebunan - Pertambangan - HTI - HPH Sistem Integrasi
Aneka Macam Bentuk Rupa Grafik
Saat ini sudah banyak model grafik yang dapat digunakan pada suatu projek, sehingga memudahkan para pengembang dalam pemrograman dibidang statistik yang berbasis web dan dapat dikoneksikan ke database, Diatas merupakan beberapa contoh dari grafik yang akan dibahas pada artikel dibawah ini :
Grafik Chandlestick Aktual Monitoring
1. Grafik Chandlestick, grafik yang sering digunakan untuk memonitoring transaksi keuangan, saham, kurs mata uang, dan lainnya, anda dapat melihat contohnya dibawah ini :
Adapun data diambil dari histori harga emas yang sudah running, jika ingin menggunakan secara real time tentu dapat dilakukan dengan cara menggunakan API jika data dari pihak kedua, jika data dari pengguna sendiri maka grafik dapat dikoneksikan langsung baik menggunakan database Mysql maupun yang lainnya. Bahasa pemrograman ini menggunakan bahasa javascript, dan dapat ditampilkan dengan bahasa Php seperti yang ada pada website xflash.
Skrip ini menggunakan plugin atau file pendukung yakni : uPlot.min.css dan uPlot.iife.js serta placement.min.js yang diletakkan diantara <head>..</head> adapun skripnya dibawah ini :
Skrip uPlot.min.css
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: max-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;border: 2px solid transparent;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;z-index: 100;}.u-cursor-x {height: 100%;border-right: 1px dashed #607D8B;}.u-cursor-y {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;filter: brightness(85%);pointer-events: none;will-change: transform;z-index: 100;}.u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
Dibawah ini adalah : file pendukung dan skrip untuk grafik chandlestick (uPlot.min.css dan uPlot.iife.js)
No | Nama File | Deskripsi | Download File |
1 | placement.min.js | file javascript (plugin) grafik | |
2 | uPlot.iife.js | file javascript (plugin) grafik | |
3 | skripchandlestick.php | file javascript (plugin) grafik | |
4 | uPlot.min.css | file javascript (plugin) grafik | |
5 | Chart.js | Grafik Jquery Versi 2.9.3 | |
6 | Chart.bundle.js | Grafik Jquery Versi 2.9.3 | |
7 | Chart.bundle.min.js | Grafik Jquery Versi 2.9.3 | |
8 | jquery.js | Jquery (js) v3.5.1 | |
9 | jquery.min.js | Jquery (min.js) v3.5.1 |
Grafik Cursor Snap Aktual Monitoring
2. Grafik Cursor Snap, grafik yang sering digunakan untuk memonitoring variance pada setiap transaksi atau sebagai perbandingan antara data vs data, grafik yang sangat membantu untuk segala transaksi yang lebih konplik, anda dapat melihat contohnya pada tombol dibawah ini :
Adapun Skrip Cursor Snap sebagai berikut :
<script> let xs = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]; let vals = [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10]; let data = [
xs,
xs.map((t, i) => vals[Math.floor(Math.random() * vals.length)]),
xs.map((t, i) => vals[Math.floor(Math.random() * vals.length)]),
xs.map((t, i) => vals[Math.floor(Math.random() * vals.length)]),
]; function roundIncr(x, incr) {
return Math.round(x/incr)*incr;} const moveTuple = [0,0]; function cursorMove(self, left, top) {
moveTuple[0] = roundIncr(left, 10);
moveTuple[1] = roundIncr(top, 10);
return moveTuple;} const opts = {
width: 1920,
height: 600,
title: "Cursor Snap (to 10x10 grid)",
cursor: {move: cursorMove},
scales: {x: {time: false,},},
series: [{},{stroke: "red",
fill: "rgba(255,0,0,0.1)",
},{stroke: "green",fill: "rgba(0,255,0,0.1)",
},{stroke: "blue",fill: "rgba(0,0,255,0.1)",
},],}; let u = new uPlot(opts, data, document.body);
</script>
Grafik Cursor Tooltip Aktual Monitoring
3. Grafik Cursor Tooltip, Grafik yang sangat sederhana namun siapa saja dapat memahami akan pergerakan pada transaksi maupun hasil dari data yang di input. adapun contohnya sebagai berikut :
Grafik ini membutuhkan file pendukung tambahan selain uPlot.min.css, dan uPilot.iife.js yakni placement.min.js, semua file merupakan open source, kita dapat merubah dan memodifikasinya, serta mengkoneksikannya sesuai kebutuhan pengembang.
Adapun skrip Grafik Cursor Tooltip sebagai berikut :
<script>
const overlay = document.createElement("div");
function tooltipPlugin(opts) {
let bound, bLeft, bTop;
overlay.id = "overlay";
overlay.style.display = "none";
overlay.style.position = "absolute";
document.body.appendChild(overlay); return {hooks: {init: u => {let can = u.root.querySelector(".u-over"); bound = can;
// bound = document.body; can.onmouseenter = () => {
overlay.style.display = "block";}; can.onmouseleave = () => {
overlay.style.display = "none";}; let bbox = can.getBoundingClientRect();
bLeft = bbox.left;
bTop = bbox.top;},
setCursor: u => {const { left, top, idx } = u.cursor; const x = u.data[0][idx]; const y = u.data[1][idx]; const anchor = { left: left + bLeft, top: top + bTop }; overlay.textContent = `${x},${y} at ${Math.round(left)},${Math.round(top)}`; placement(overlay, anchor, "right", "start", { bound });
}}};} const opts = {id: "chart",title: "placement.js tooltip", width: 600,
height: 400,
plugins: [
tooltipPlugin(),],
scales: {x: {time: false,} }, series: [ {},{label: "blah", width: 1, stroke: "green" }] }; const data = [[ 1, 2, 3, 4, 5, 6, 7],
[40, 43, 60, 65, 71, 73, 80]]; const u = new uPlot(opts, data, document.body);
</script>
Grafik dependent drived Scale Aktual Monitoring
4. Grafik dependent drived Scale, Grafik yang cocok untuk memonitoring suhu atau Curah hujan, tampilan sangat sederhana dan mudah untuk membaca data., bentuk rupa tampilannya sebagai berikut :
Adapun skripnya sebagai berikut :
<script>
function makeChart() {
console.time('chart');let opts = {
title: "Derived Scale",
width: 600,
height: 400,
scales: {x: {time: false},z: {from: 'y',
range: (u, min, max) => [(min - 32) * 5/9, (max - 32) * 5/9],
}},
series: [{},{label: "blah",stroke: "green",},],
axes: [{},{values: (u, vals, space) => vals.map(v => v + '° F'),
},{scale: 'z',range: (u, min, max) => [Math.ceil(min), Math.ceil(max)],
values: (u, vals, space) => vals.map(v => v + '° C'),
side: 1,
grid: {show: false},
space: 20,}],}; const data = [[ 1, 2, 3, 4, 5, 6, 7],[40,43,60,65,71,73,80],];let u = new uPlot(opts, data, document.body); console.timeEnd('chart');} makeChart();
</script>
Grafik draw hooks Aktual Monitoring
5. Grafik draw hooks, grafik yang bertampilan sederhana dan sangat cocok untuk memonitoring transaksi apa saja yang memiliki banyak item seperti, penjualan barang, pekerjaan dan lain-lain. adapun wujud aslinya seperti dibawah ini :
Adapun skrip untuk draw hooks sebagai berikut :
<script> "use strict";function bgGradientPlugin({ stops = ['#FFFFFF', '#CCCCCC'] } = {}) {
function drawBg(u) {
let { left, top, width, height } = u.bbox;
let gradient = u.ctx.createLinearGradient(0, 0, 0, height);for (let c = 0; c < stops.length; c++)
u.ctx.save();
gradient.addColorStop(c, stops[c]);
u.ctx.fillStyle = gradient;
u.ctx.fillRect(left, top, width, height);
u.ctx.restore();
}return {hooks: {drawClear: drawBg,}};} function gridBlurPlugin({ radius = 2 } = {}) {function applyBlur(u) {
let { left, top, width, height } = u.bbox;u.ctx.save();
function stopBlur(u) {u.ctx.restore();}
// u.ctx.rect(left, top, width, height);
// u.ctx.clip();
u.ctx.filter = 'blur(' + radius + 'px)';}return {hooks: {drawClear: applyBlur,drawAxes: stopBlur,}};}
function seriesMediansPlugin({ lineWidth = 50, blur = 6 } = {}) {lineWidth *= devicePixelRatio;let medians;
function hexToRgbA(hex, a) {hex = hex.replace('#', '');if (hex.length == 3)
hex = hex.split('').map(c => c.repeat(2)).join(''); let r = parseInt(hex.substring(0, 2), 16);
let g = parseInt(hex.substring(2, 4), 16);
let b = parseInt(hex.substring(4, 6), 16);return 'rgba('+r+','+g+','+b+','+a+')';}
// https://www.jstips.co/en/javascript/array-average-and-median/
function drawSeriesMedian(u, i) {
function calculateMedians(u) {
medians = u.data.map(data => {
data = [...data];
data.sort((a, b) => a - b);
return (data[(data.length - 1) >> 1] + data[data.length >> 1]) / 2
});}
let { ctx } = u;
let { left, top, width, height } = u.bbox;
let { stroke, scale } = u.series[i]; let cy = Math.round(u.valToPos(medians[i], scale, true));ctx.save();
if (blur)
ctx.beginPath();
ctx.rect(left, top, width, height);
ctx.clip();
ctx.strokeStyle = hexToRgbA(stroke, 0.2);
ctx.lineWidth = lineWidth;
ctx.filter = 'blur(' + blur + 'px)'; ctx.beginPath();
ctx.moveTo(left, cy);
ctx.lineTo(left + width, cy);
ctx.closePath();
ctx.stroke();
ctx.restore();}return {hooks: {setData: calculateMedians,drawSeries: drawSeriesMedian,}};}
function seriesPointsPlugin({ spikes = 4, outerRadius = 8, innerRadius = 4} = {}) {
// https://stackoverflow.com/questions/25837158/how-to-draw-a-star-by-using-canvas-html5
outerRadius *= devicePixelRatio;
innerRadius *= devicePixelRatio;
function drawStar(ctx, cx, cy) {
let rot = Math.PI / 2 * 3;
let x = cx;
let y = cy;
let step = Math.PI / spikes; ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius); for (let i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y);
rot += step; x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y);
rot += step;}ctx.lineTo(cx, cy - outerRadius);
ctx.closePath();}function drawPointsAsStars(u, i, i0, i1) {let { ctx } = u;let { stroke, scale } = u.series[i];
ctx.fillStyle = stroke;let j = i0;while (j <= i1) {
return {opts: (u, opts) => {opts.series.forEach((s, i) => {
let val = u.data[i][j];
let cx = Math.round(u.valToPos(u.data[0][j], 'x', true));
let cy = Math.round(u.valToPos(val, scale, true));
drawStar(ctx, cx, cy);
ctx.fill();
j++;};}
if (i > 0) {uPlot.assign(s, {points: {show: drawPointsAsStars,}});}
});
}};
}function renderStatsPlugin({ textColor = 'red', font = '12px Arial'} = {}) {
function setStartTime() {
let startRenderTime;
startRenderTime = Date.now();
}function drawStats(u) {
let { ctx } = u;
let { left, top, width, height } = u.bbox;
let displayText = "Time to Draw: " + (Date.now() - startRenderTime) + "ms";ctx.font = font;
return {hooks: {drawClear: setStartTime,draw: drawStats,}};}
ctx.fillStyle = textColor;
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText(displayText, left + 10, top + 10);}function makeChart() {const data = [
const grid = {show: true,stroke: '#000',};
[ 1, 2, 3, 4, 5, 6, 7, 9,10],
[40,43,60,65,71,73,40,22,20],
[30,23,35,27,11,13,30,32,30],
[15,13,39,17,21,53,10,11,13],
];const tick = {show: true,stroke: '#000',size: 10,};
let opts = {title: "Draw Hooks",width: 600,height: 400,cursor: {points: {show: false,}},
let u = new uPlot(opts, data, document.body);} makeChart();
axes: [{grid, tick},{grid, tick},],
scales: {x: {time: false},},plugins: [bgGradientPlugin({ stops: ['#666', '#000'] }),
//gridBlurPlugin(),
seriesMediansPlugin(),
seriesPointsPlugin({ spikes: 6}),
renderStatsPlugin({ textColor: 'white' }),
],
series: [{},{label: "blah",stroke: "#ff3333",},{label: "yerp",stroke: "#33ccff",},{
label: "zort",stroke: "#ffcc33",}]};
</script>
Grafik ini tetap mengundang file pendukung yang sudah dijelaskan pada pembahasan sebelumnya.