chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
63.92k stars 11.89k forks source link

How can I display title text on a pie chart in v4 #11698

Closed CarsonSlovoka closed 4 months ago

CarsonSlovoka commented 4 months ago

Expected behavior

show Title text on pie or doughnut

Current behavior

Only the legend, no title.

Reproducible sample

https://codepen.io/CarsonJK/pen/vYMYMeY

Optional extra steps/info to reproduce

No response

Possible solution

No response

Context

No response

chart.js version

v4.4.2

Browser name and version

Chrome

Link to your project

No response

LeeLenaleee commented 4 months ago

The title has to be configured in the plugins namespace. If you do that it works correctly: https://www.chartjs.org/docs/4.4.0/configuration/title.html

image

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2"></script>
<body></body>
<script>
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d');
  new Chart(ctx, {
    type: 'pie',
    data: {
      labels: ['Red', 'Blue', 'Yellow'],
      datasets: [{
        label: 'My First Dataset',
        data: [300, 50, 100],
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: 'Custom Chart Title',
          fontSize: 18,
          position: 'top'
        }
      }
    }
  })
  document.body.append(canvas)
</script>
CarsonSlovoka commented 4 months ago

~fontSize~ => font: {size: xxx}

plugins: {
  title: {
    display: true,
    text: "my title",
    // position: 'bottom' // default: top
    font: {
      size: 50
    }
  },
}