Widget:Grafico
Da WikiLectio.
<canvas id="canvas_{{{id}}}" width="600" height="380"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script> // --- Helpers: parsing da parametri wikitext --- function parseCSVNumbers(str) {
if (!str) return [];
return str.split(',').map(s => {
const v = s.trim();
const n = Number(v);
return isNaN(n) ? null : n;
});
} function parseCSVStrings(str) {
if (!str) return [];
return str.split(',').map(s => s.trim());
} function colorOrNull(s){ return (s && s.trim()) ? s.trim() : null; }
// --- Costruzione datasets dinamici (fino a 4 serie) --- (function(){
var id = "{{{id}}}";
var ctx = document.getElementById("canvas_{{{id}}}").getContext("2d");
var labels = parseCSVStrings("0,2,4,6,8,10");
var datasets = [];
// Serie 1..4: title, data, type (line/bar), color
var series = [
{t: "", d: "", ty: "line", c: ""},
{t: "", d: "", ty: "line", c: ""},
{t: "", d: "", ty: "line", c: ""},
{t: "", d: "", ty: "line", c: ""}
];
series.forEach(function(s){
if (!s.t || !s.d) return;
var dataArr = parseCSVNumbers(s.d).map(v => (v===null? null : v));
datasets.push({
label: s.t,
data: dataArr,
type: (s.ty && s.ty.trim()) || 'line',
fill: false,
borderColor: colorOrNull(s.c),
backgroundColor: colorOrNull(s.c),
tension: 0, // linee dritte (0), o 0.2 per un po' di curva
pointRadius: 2
});
});
// Opzioni var chartTitle = ""; var xTitle = "Quantità di appartamenti"; var yTitle = "Prezzo dell'affitto"; var showLegend = "true".toLowerCase() !== "false"; var responsive = "true".toLowerCase() !== "false";
// Limiti assi (opzionali)
function numOrUndef(x){ var n = Number(x); return isNaN(n) ? undefined : n; }
var yMin = numOrUndef("");
var yMax = numOrUndef("");
var xMin = numOrUndef("");
var xMax = numOrUndef("");
// Se labels sono numeriche, abilita asse X numerico
var numericLabels = labels.every(l => !isNaN(Number(l)));
var dataConfig = {
labels: labels,
datasets: datasets
};
new Chart(ctx, {
type: 'line',
data: dataConfig,
options: {
responsive: responsive,
maintainAspectRatio: false,
plugins: {
title: {
display: !!chartTitle,
text: chartTitle
},
legend: { display: showLegend },
tooltip: { enabled: true }
},
scales: {
x: numericLabels ? {
type: 'linear',
title: { display: true, text: xTitle },
min: xMin, max: xMax,
ticks: { callback: function(value){ return value; } }
} : {
type: 'category',
title: { display: true, text: xTitle }
},
y: {
title: { display: true, text: yTitle },
min: yMin, max: yMax,
beginAtZero: false
}
},
elements: {
line: { borderWidth: 2 }
}
}
});
})(); </script>