chart.js 如何使 x 轴标签位于顶部

chart.js how to make x-axis labels position top

我是 chart.js 的新手,我有一个关于将 x 轴标签定位到顶部的问题。

This 是我预期的结果:x 轴标签在顶部。

这是我的尝试:

const ctx = document.getElementById('weather_chart');
const myChart = new Chart(ctx, {
    data: {
        datasets: [{
            type: 'bar',
            label: 'rainfall probability',
            data: [10, 20, 30, 40],
        }, {
            type: 'line',
            label: 'temperature',
            data: [50, 50, 50, 50],
            borderColor: '#EB6E4B',
            backgroundColor: '#EB6E4B',
        }],
        labels: ['now', '9am', '10am', '11am', '12pm'],
    },
    options: {
        plugins: {
            legend: {
                display: false,
            },
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="chart">
  <canvas id="weather_chart"></canvas>
</div>

如果可以的话,你会花时间写下答案吗?

在此先感谢,如果我的问题还不够,请告诉我。

在 options > scales > xAxes 里面,xAxes 是一个数组,所以我们可以定义多个轴,然后配置如下:

options:{
    scales: {
        xAxes: [
            {
                position: 'top',
                ticks: {
                    maxRotation: 90,
                    minRotation: 80
                }
            }
        ]
    }
}

在此处查看示例 https://codepen.io/ganeshbkdm/pen/oNeaOwm

您可以在此命名空间中配置所有与比例相关的内容,例如位置:options.scales[scaleId]。有关秤的更多配置选项,您可以阅读文档:https://www.chartjs.org/docs/master/axes/

const ctx = document.getElementById('weather_chart');
const myChart = new Chart(ctx, {
  data: {
    datasets: [{
      type: 'bar',
      label: 'rainfall probability',
      data: [10, 20, 30, 40],
    }, {
      type: 'line',
      label: 'temperature',
      data: [50, 50, 50, 50],
      borderColor: '#EB6E4B',
      backgroundColor: '#EB6E4B',
    }],
    labels: ['now', '9am', '10am', '11am', '12pm'],
  },
  options: {
    scales: {
      x: {
        position: 'top'
      }
    },
    plugins: {
      legend: {
        display: false,
      },
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="chart">
  <canvas id="weather_chart"></canvas>
</div>