He dibujado un gráfico de líneas usando chart.js. Para las etiquetas y los conjuntos de datos, obtengo valores de la base de datos. Soy nuevo en chart.js y su biblioteca muy poderosa, pero no puedo entenderlo por completo. Quiero dibujar múltiples líneas horizontales. Como dónde si la media del conjunto de datos, la desviación estándar y el mínimo y el máximo. Intenté la pregunta aquí en stackoverflow, pero estos están dando errores o es posible que no pueda entender el funcionamiento. Este es mi código chart.js
function display_graph(id, label, data) { var ctx = document.getElementById(id); var data = { labels: data.labels, datasets: [ { label: label, fill: false, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderWidth: 1, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: data.assay_value, spanGaps: false } ] }; //options var options = { responsive: true, title: { display: true, position: "top", text: label, fontSize: 18, fontColor: "#111" }, legend: { display: true, position: "bottom", labels: { fontColor: "#333", fontSize: 16 } } }; var Blanks_Chart=null; Blanks_Chart = new Chart(ctx, { type: 'line', data: data, options: options });}Puede usar el complemento de anotación chart.js para dibujar fácilmente líneas en su gráfico sin tener que meterse con la representación manual de píxeles en su lienzo (el enfoque antiguo que le está dando errores). Tenga en cuenta que el complemento es creado y respaldado por el mismo equipo que chart.js y se menciona en los documentos de chart.js .
Aquí hay un codepen de ejemplo que demuestra la creación de una línea en un gráfico.
Una vez que agregue el complemento, simplemente configure las propiedades de annotation en la configuración de su gráfico. Aquí hay un ejemplo.
var myChart = new Chart(ctx, { type: 'line', data: { labels: ["January", "February"], datasets: [{ label: 'Dataset 1', borderColor: window.chartColors.blue, borderWidth: 2, fill: false, data: [2, 10] }] }, options: { responsive: true, title: { display: true, text: 'Chart.js Draw Line On Chart' }, tooltips: { mode: 'index', intersect: true }, annotation: { annotations: [{ type: 'line', mode: 'horizontal', scaleID: 'y-axis-0', value: 5, borderColor: 'rgb(75, 192, 192)', borderWidth: 4, label: { enabled: false, content: 'Test label' } }] } } });Si desea dibujar una línea de umbral, la forma más fácil es usar un gráfico de líneas mixtas.
Nota: Cree una matriz llena con el valor del umbral y la longitud debe ser la misma que su conjunto de datos.
var datasets = [1, 2, 3]; var ctx = document.getElementById('chart').getContext('2d'); var thresholdValue = 2; var thresholdHighArray = new Array(datasets.length).fill(thresholdValue); var myChart = new Chart(ctx, { type: 'line', data: { labels: [], datasets: [ {datasets}, thresholdHighArray] }, options: { responsive: true, legend: { position: 'bottom', }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Readings' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Reading ( °C )' } }] }, annotation: { annotations: [ { type: "line", mode: "vertical", scaleID: "x-axis-0", borderColor: "red", label: { content: "", enabled: true, position: "top" } } ] } }); };Si está utilizando el paquete NPM chartjs-plugin-annotation.js , lo importante, que puede olvidar, es registrar el complemento.
Entonces, antes que nada, instaló los paquetes npm (aquí para React ):
npm i react-chartjs-2 (depends on your framework) npm i chartjs-plugin-annotation (always required)Consulte Vue.js o Angular para conocer los paquetes que dependen de su marco.
Opción 1: registro de complemento global
import { Line } from 'react-chartjs-2'; import Chart from 'chart.js'; import * as ChartAnnotation from 'chartjs-plugin-annotation'; Chart.plugins.register([ChartAnnotation]); // Global // ... render() { return ( <Line data={chartData} options={chartOpts} /> ) }Opción 2: registro de complemento por gráfico
import { Line } from 'react-chartjs-2'; import * as ChartAnnotation from 'chartjs-plugin-annotation'; // ... render() { return ( {/* per chart */} <Line data={chartData} options={chartOpts} plugins={[ChartAnnotation]} /> ) } chartData es equivalente a los data: { sección y chartOpts to options: { from jordanwillis answer . Consulte esta publicación de github para obtener más información.
Hay muchos otros complementos disponibles para chart.js.