【问题标题】:ChartJS x-axis show only months of yearChartJS x 轴仅显示一年中的几个月
【发布时间】:2020-01-03 22:27:53
【问题描述】:

所以我正在使用 Cordova 制作这个移动应用程序,它允许我使用 HTML、CSS 和 JavaScript。我目前正在使用 SQLite 作为数据库(与 mySQL 几乎相同),但这并不重要。我所做的就是从那个数据库中获取我的数据。我得到了日期(数据添加到数据库的时间)和一个人的体重。

我正在使用一个折线图,它在 Y 轴上显示重量,在 X 轴上显示数据。

我想要做的只是将月份显示为 x 轴上的标签,但仍然让它显示每天的数据。例如,如果我在 1 月 1 日、1 月 2 日和 1 月 3 日添加数据。我希望能够在图表上将所有 3 天都视为点,但在 X 轴上应该只显示“一月”。

我一直在研究 Chart.JS 的“时间”选项,但无法真正理解我应该如何做。

HTML:

<canvas id="myChart" style="margin-top: 20px;"></canvas>

JavaScript:

//these are the arrays that I will fill dynamically. Labels will be my months and data will be the weight

var labels = []; 
var data = [];

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: labels,
        datasets: [{
            backgroundColor: 'rgba(255, 119, 0, 0.5)',
            borderColor: 'rgba(255, 119, 0, 1)',
            data: data
        }]
    },

    // Configuration options go here
    options: {
        legend: {
            display: false
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

【问题讨论】:

    标签: javascript sqlite cordova chart.js


    【解决方案1】:

    在 x 轴上使用时间类型。使用time: { unit: 'month' }(始终为月)或minUnit(必要时为月和年),您可以获得月标签。

    作为数据的标签,您需要传递 Datemoment

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'month'
        }
      }],
    }
    

    Here 是一个完整的例子。 检查moment docs 的日期,尤其是日期的创建和解析。 Chart.js 适用于时刻日期,因此它非常重要(顺便说一句也很简单)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多