• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

1K
Views
Chart.js — dibujar una línea vertical arbitraria

¿Cómo puedo dibujar una línea vertical en un punto particular en el eje x usando Chart.js?

En particular, quiero dibujar una línea para indicar el día actual en un LineChart. Aquí hay una maqueta del gráfico: http://i.stack.imgur.com/VQDWR.png

ingrese la descripción de la imagen aquí

over 3 years ago · Santiago Trujillo
3 answers
Answer question

0

Actualización : esta respuesta es para Chart.js 1.x, si está buscando una respuesta 2.x, consulte los comentarios y otras respuestas.

Extienda el gráfico de líneas e incluya lógica para dibujar la línea en la función de dibujo.


Avance

ingrese la descripción de la imagen aquí


HTML

 <div> <canvas id="LineWithLine" width="600" height="400"></canvas> </div>

Texto

 var data = { labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"], datasets: [{ data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1] }] }; var ctx = document.getElementById("LineWithLine").getContext("2d"); Chart.types.Line.extend({ name: "LineWithLine", draw: function () { Chart.types.Line.prototype.draw.apply(this, arguments); var point = this.datasets[0].points[this.options.lineAtIndex] var scale = this.scale // draw line this.chart.ctx.beginPath(); this.chart.ctx.moveTo(point.x, scale.startPoint + 24); this.chart.ctx.strokeStyle = '#ff0000'; this.chart.ctx.lineTo(point.x, scale.endPoint); this.chart.ctx.stroke(); // write TODAY this.chart.ctx.textAlign = 'center'; this.chart.ctx.fillText("TODAY", point.x, scale.startPoint + 12); } }); new Chart(ctx).LineWithLine(data, { datasetFill : false, lineAtIndex: 2 });

La propiedad de opción lineAtIndex controla en qué punto dibujar la línea.

Violín - http://jsfiddle.net/dbyze2ga/14/

over 3 years ago · Santiago Trujillo Report

0

Compartiendo mi solución para chartjs.org versión 2.5. Quería usar un complemento para hacer que la implementación sea reutilizable.

 const verticalLinePlugin = { getLinePosition: function (chart, pointIndex) { const meta = chart.getDatasetMeta(0); // first dataset is used to discover X coordinate of a point const data = meta.data; return data[pointIndex]._model.x; }, renderVerticalLine: function (chartInstance, pointIndex) { const lineLeftOffset = this.getLinePosition(chartInstance, pointIndex); const scale = chartInstance.scales['y-axis-0']; const context = chartInstance.chart.ctx; // render vertical line context.beginPath(); context.strokeStyle = '#ff0000'; context.moveTo(lineLeftOffset, scale.top); context.lineTo(lineLeftOffset, scale.bottom); context.stroke(); // write label context.fillStyle = "#ff0000"; context.textAlign = 'center'; context.fillText('MY TEXT', lineLeftOffset, (scale.bottom - scale.top) / 2 + scale.top); }, afterDatasetsDraw: function (chart, easing) { if (chart.config.lineAtIndex) { chart.config.lineAtIndex.forEach(pointIndex => this.renderVerticalLine(chart, pointIndex)); } } }; Chart.plugins.register(verticalLinePlugin);

El uso es simple entonces:

 new Chart(ctx, { type: 'line', data: data, label: 'Progress', options: options, lineAtIndex: [2,4,8], })

El código anterior inserta líneas verticales rojas en las posiciones 2, 4 y 8, pasando por los puntos del primer conjunto de datos en esas posiciones.

over 3 years ago · Santiago Trujillo Report

0

Recomiendo encarecidamente usar Chartjs-Plugin-Annotation .

Un ejemplo se puede encontrar en CodePen

 var chartData = { labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"], datasets: [ { data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1] } ] }; window.onload = function() { var ctx = document.getElementById("canvas").getContext("2d"); new Chart(ctx, { type: "line", data: chartData, options: { annotation: { annotations: [ { type: "line", mode: "vertical", scaleID: "x-axis-0", value: "MAR", borderColor: "red", label: { content: "TODAY", enabled: true, position: "top" } } ] } } }); };

Eche un vistazo aquí para obtener más detalles: https://stackoverflow.com/a/36431041

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error