Chart.js Customizing Tick Labels for Mixed Font Styles
Asked Answered
D

0

1

I am building a chart with React and Chart.js, and I need to display tick labels that have mixed font styles. Chart.js returns the tick values as a string of the the text passed in as well as the HTML tags that wrap the values we want to italicize.

I tried writing a callback function to return jsx which nulled out the y axis tick marks. Additionally, I have tried applying conditions to the fontStyle prop, and customizing the html in the labels.

let italicizedFont = 'Font'.italics()
console.log(italicizedFont)
var myChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ["Normal Font", "Mixed <i>Font</i>", `Mixed ${italicizedFont}`, 'Mixed font in <i>Return</i>'],
    datasets: [{
      data: [12, 19, 8],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    responsive: false,
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      yAxes: [{
        ticks: {
          callback: (value, i, values) => {
            if(i !== 3 ){
              return value
            }
            return values[3].replace(/<i>/g, '').replace(/<\/i>/g, '')
        },
          // fontStyle:  'italic'
        }
      }]
    }
  }
});

Code Pen Example

I would expect that Chart.js would convert the string "normal text italicized text" to a string. However, Chart.js seems capable of only returning a fully italicized string "normal text italicized text" or a string with the html tags included.

Dali answered 30/8, 2019 at 18:11 Comment(4)
Please supply a working codepen...Liquescent
Can you utilize this link? codepen.io/faltherr/pen/jONLVjd?editors=1011 or CodepenDali
From what I can tell this is only possible when using radar type.. I found this fiddle online, as well as this SO answer explaining how the labels are rendered when using bar or line.. For good measure, here is another fiddle that I found online. Stinks that they don't let you put html in the labels...Liquescent
I am following this question, looking for solution, please helpRiverine

© 2022 - 2024 — McMap. All rights reserved.