Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

738
Vistas
cómo cambiar el color de las etiquetas de las leyendas de chart.js

Uso el paquete chart.js para crear un gráfico.

mi problema: ¿cómo cambiar el color de la etiqueta de cada leyenda?

por ejemplo:

  1. color de "leyenda1" ser: rojo.
  2. color de "leyenda2" ser: azul.

mis codigos:

 const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { data: { labels: ['۱۴۰۰/۰۱/۰۱', '۱۴۰۰/۰۱/۰۲', '۱۴۰۰/۰۱/۰۳', '۱۴۰۰/۰۱/۰۴', '۱۴۰۰/۰۱/۰۵', '۱۴۰۰/۰۱/۰۶'], datasets: [{ type: 'line', label: 'legend1', backgroundColor: 'rgb(14, 156, 255)', data: [6, 5.5, 4, 7, 5.4, 5.8], fill: false, borderColor: 'rgb(14, 156, 255)', tension: 0 }, { type: 'line', label: 'legend2', backgroundColor: 'rgb(22, 185, 156)', data: [6.2, 5.7, 3.8, 7.2, 5.2, 5.9], fill: false, borderColor: 'rgb(22, 185, 156)', tension: 0 } ] //end : datasets }, // end: data options: { plugins: { legend: { labels: { font: { size: 18 } // end: font } // end: labels , position: 'bottom', rtl: true, align: "start" } // end: legend }, // end: plugins scales: { y: { beginAtZero: true, display: false } // end: y , x: { grid: { borderDash: [6, 5], lineWidth: 1, color: '#CCCCCC' } // end: grid } //end:x } // end: scales } //end: options });
 <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script> <canvas id="myChart" width="778" height="433"></canvas>

mi problema es solo ese: ¿cómo cambiar el color del texto de cada leyenda? color del texto "leyenda1" y color del texto "leyenda2".

resultado de mis códigos: ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Para lograr lo que desea, deberá usar una función de generateLabels etiquetas personalizada como esta:

 const legendColors = ['red', 'blue'] const options = { type: 'line', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderColor: 'pink' }, { label: '# of Points', data: [7, 11, 5, 8, 3, 7], borderColor: 'orange' } ] }, options: { plugins: { legend: { labels: { generateLabels: (chart) => { const datasets = chart.data.datasets; const { labels: { usePointStyle, pointStyle, textAlign, color } } = chart.legend.options; return chart._getSortedDatasetMetas().map((meta, i) => { const style = meta.controller.getStyle(usePointStyle ? 0 : undefined); const borderWidth = Chart.helpers.toPadding(style.borderWidth); return { text: datasets[meta.index].label, fillStyle: style.backgroundColor, fontColor: legendColors[i], hidden: !meta.visible, lineCap: style.borderCapStyle, lineDash: style.borderDash, lineDashOffset: style.borderDashOffset, lineJoin: style.borderJoinStyle, lineWidth: (borderWidth.width + borderWidth.height) / 4, strokeStyle: style.borderColor, pointStyle: pointStyle || style.pointStyle, rotation: style.rotation, textAlign: textAlign || style.textAlign, borderRadius: 0, // TODO: v4, default to style.borderRadius // Below is extra data used for toggling the datasets datasetIndex: meta.index }; }, this); } } } } } } const ctx = document.getElementById('chartJSContainer').getContext('2d'); new Chart(ctx, options);
 <body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script> </body>

about 4 years ago · Juan Pablo Isaza Denunciar

0

¿Probaste el formato hexadecimal? Por ejemplo, podría intentar reemplazar "rgb(14, 156, 255)" por "#0e9cff"

Más información aquí: https://devsheet.com/code-snippet/change-color-of-the-line-in-chartjs-line-chart/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda