【问题标题】:chart.js how to make x-axis labels position topchart.js 如何使 x 轴标签位于顶部
【发布时间】:2021-11-15 03:15:16
【问题描述】:

我是 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>

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

提前致谢,如果我的问题不够充分,请告诉我。

【问题讨论】:

  • 你能告诉我们你所做的任何尝试吗?看看这个stackoverflow.com/help/how-to-ask
  • 哦,我错过了。我真的很抱歉。我编辑了它,这会起作用吗?

标签: javascript chart.js x-axis


【解决方案1】:

您可以在此命名空间中配置所有与比例相关的内容,例如位置: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>

【讨论】:

    【解决方案2】:

    inside options > scales > xAxes xAxes 是一个数组,所以我们可以定义多个轴,并有这样的配置:

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

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

    【讨论】:

    • 不行,他用的是V3,不是V2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多