如何更改图表中的X轴标签位置。 X轴标签应在图表内而不是外部显示

发布于 2025-01-20 09:12:41 字数 186 浏览 3 评论 0原文

Invision Image链接此处

我使用的是Angular 13和Chart.js 3.7.1。我想让X轴标签应在栏旁边和图表内移动,而不是在图表外显示。

Invision Image link here

I am using Angular 13 and chart.js 3.7.1. I would like to have the x-axis labels should be moved beside the bar and inside the chart instead of displayed outside of the chart.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小ぇ时光︴ 2025-01-27 09:12:41

这可以通过 chartjs-plugin-datalabels 来完成。它提供了许多用于定位标签的选项

请看一下下面的可运行代码,看看它是如何完成的。

Chart.register(ChartDataLabels);
new Chart("barChart", {
  type: 'bar',
  data: {
    labels: ['One', 'Two', 'Three', 'Four'],
    datasets: [{
      label: 'Data',
      data: [5, 8, 24, 14],
      backgroundColor: 'rgb(124, 124, 255)'
    }]
  },
  options: {
    plugins: {
      datalabels: {
        align: 'left',
        rotation: -90,
        offset: 50,
        font: {
          weight: 'bold'
        },
        formatter: (v, ctx) => ctx.chart.data.labels[ctx.dataIndex]
      }
    },
    scales: {
      x: {
        ticks: {
          display: false
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
<canvas id="barChart" height="100"></canvas>

This can be done with chartjs-plugin-datalabels. It offers many options for positioning the labels.

Please take a look at below runnable code and see how it could be done.

Chart.register(ChartDataLabels);
new Chart("barChart", {
  type: 'bar',
  data: {
    labels: ['One', 'Two', 'Three', 'Four'],
    datasets: [{
      label: 'Data',
      data: [5, 8, 24, 14],
      backgroundColor: 'rgb(124, 124, 255)'
    }]
  },
  options: {
    plugins: {
      datalabels: {
        align: 'left',
        rotation: -90,
        offset: 50,
        font: {
          weight: 'bold'
        },
        formatter: (v, ctx) => ctx.chart.data.labels[ctx.dataIndex]
      }
    },
    scales: {
      x: {
        ticks: {
          display: false
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
<canvas id="barChart" height="100"></canvas>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文