【问题标题】:How to label x-Axis in Chart.js by days?如何在 Chart.js 中按天标记 x 轴?
【发布时间】:2018-01-27 11:06:27
【问题描述】:

我目前正在尝试从 blockchain.info 获取数据并将其显示在一个简单的 JavaScript 文件中的 Chart.js 上。

如果我的 xAxes 类型是“线性”,它就可以正常工作,但在这种情况下,x 轴上的标签会显示带有数字 unix 时间戳。

xAxes: [{
    type: 'linear',
    time: {
        unit: 'day',
        tooltipFormat: 'lll',
    }
}]

我希望标签以天数显示(例如 2018 年 1 月 27 日)或按月分组(图表上 30 个点,1 个标签 -> 月)。出于这个原因,我将 xAxes 类型更改为“时间”,然后导致以下错误:

“未捕获的错误:Chart.js - 找不到 Moment.js!您必须在 Chart.js 之前包含它才能使用时间刻度。在 https://momentjs.com 下载”。

我玩过 momentjs 并将其包含在 script 标签中。很遗憾我没能解决这个问题。

我的 JSON 中的数据如下所示:

{
  "status": "ok",
  "name": "Confirmed Transactions Per Day",
  "unit": "Transactions",
  "period": "day",
  "description": "The number of daily confirmed Bitcoin transactions.",
  "values": [
    {
      "x": 1442534400, // Unix timestamp (2015-09-18T00:00:00+00:00)
      "y": 188330.0
    },
    ...
}

这是我的完整代码:

    var requestURL = 'https://blockchain.info/de/charts/market-price?format=json&cors=true';
    var request = new XMLHttpRequest();

    request.open('GET', requestURL);
    request.responseType = 'json';
    request.send();
    request.onload = function() {
        var response = request.response;
        drawChart(response);
    }

    function drawChart(jsonObj) {

        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: jsonObj["values"],
                datasets: [{
                    label: jsonObj["name"],
                    data: jsonObj["values"],
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }],
                    xAxes: [{
                        type: 'time',
                        time: {
                            unit: 'day',
                            tooltipFormat: 'lll',
                        }
                    }]                    
                }
            }
        });            
    }   
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<script src="node_modules/chart.js/dist/Chart.js"></script>
<script srx="myChart.js"></script>
<body>
    <canvas id="myChart" width="100%" height="100%"></canvas>
</body>
</html>

【问题讨论】:

    标签: javascript chart.js blockchain.info-api


    【解决方案1】:

    在上图中你可以看到数据,注意我将它分成三个数组,在图表中我有两个数据集(Ingreso(x[date],y[value]), Egreso(x[date], y[vlue])) 和“标签”,即填充 x 轴标签的标签。这就是我的做法!

    所以在标签选项中我用我的标签数组填充日期

    【讨论】:

      【解决方案2】:

      我运行您的脚本,在每个点显示金钱的方式上进行了一些改进,但由于查询返回 365 个元素的数据太多,无法在图表中显示,这就是为什么我认为有重叠标签的原因。我注意到数组中的每个值都有相同的日期(Sat Jan 17 1970 xx:yy:zz 和 Sun Jan 18 1970 qq:ww:ee)但不同的时间.. 然后我按这些日期对数据进行分组,如下所示:

      这是整个脚本。

      $('#getData').on('click', function(){
      		var requestURL = 'https://blockchain.info/de/charts/market-price?format=json&cors=true';    
      		var request = new XMLHttpRequest();
      		let newData = [], labels = [];
      		let sameDate = "", previousDate = "", value = 0;
      		request.open('GET', requestURL);
      		request.responseType = 'json';
      		request.send();
      		request.onload = function() {
      			
      			// Group the Data by Day
      			request.response.values.forEach(function(item,i){
      				if (previousDate !== getDateFormat(moment(item.x)._d) )
      				{
      					value = 0;
      					value = item.y;
      					
      					sameDate = getDateFormat(moment(item.x)._d);
      					
      					request.response.values.forEach(function(ele, j){
      						if ( j > i){
      							if (sameDate === getDateFormat(moment(ele.x)._d)){
      								value+= ele.y;
      								previousDate = getDateFormat(moment(ele.x)._d);
      							}
      						}
      						
      					});
      					newData.push({x:sameDate, y:value});
      					labels.push(sameDate);
      				}
      			});
      			
      		    drawChart(newData,labels);
      		}
      
      		function getDateFormat(momentType)
      		{
      			console.log(momentType);
      			return momentType.getDate()+"-"+(momentType.getMonth()+1)+"-"+momentType.getUTCFullYear();
      		}
      
      		function drawChart(jsonObj,label) {
      
      		    var ctx = document.getElementById("myChart");
      		    var myChart = new Chart(ctx, {
      		        type: 'line',
      		        data: {
      		            labels: label,
      		            datasets: [{
      		            	label: "Average USD",
      		            	data:jsonObj}]
      		        },
      		        options: {
      		            scales: {
      		                yAxes: [{
      		                    ticks: {
      		                        beginAtZero:true
      		                    }
      		                }],
      		                xAxes: [{
      		                    display: true,
      		                    scaleLabel: {
      		                        display: true,
      		                        labelString: 'value'
      		                    }                        
      		                }]                    
      		            },
      		            plugins: {
      		            	datalabels:{
      		            		borderRadius: 4,
      							color: 'black',
      							anchor: 'end',
      							align: 'end',
      							backgroundColor: function(context) {
      								return context.dataset.borderColor;
      							},
      							formatter: function(value, context){
      								// show the value on the point
      								return Number(value.y).toFixed(2);
      							},
      		            	}
      		            }
      		        }
      		    });            
      		}    
      	});

      【讨论】:

        【解决方案3】:

        此外,这是我的整个脚本。

            var requestURL = 'https://blockchain.info/de/charts/market-price?format=json&cors=true';    
        var request = new XMLHttpRequest();
        
        request.open('GET', requestURL);
        request.responseType = 'json';
        request.send();
        request.onload = function() {
            var response = request.response;
            drawChart(response);
        }
        
        function fillLabel(jsonObj){
            var label = [];
            var arr = jsonObj["values"];
            arr.forEach(element => {
                label.push((element.x));    
            });    
            return label;
        }
        
        function drawChart(jsonObj) {
        
            var ctx = document.getElementById("myChart");
            var myChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: fillLabel(jsonObj),
                    datasets: [{
                        label: jsonObj["name"],
                        data: jsonObj["values"],
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }],
                        xAxes: [{
                            type: 'time',
                            time: {
                                unit: 'second',
                                displayFormats: {
                                    millisecond: 'h:mm:ss.SSS a',
                                    second: 'D MMM',
                                    minute: 'D MMM',
                                    hour: 'hA',
                                    day: 'MMM D',
                                    week: 'll',
                                    month: 'MMM YYYY',
                                    quarter: '[Q]Q - YYYY',
                                    year: 'YYYY'
                                },                            
                            },
                            display: true,
                            scaleLabel: {
                                display: true,
                                labelString: 'value'
                            }                        
                        }]                    
                    }
                }
            });            
        }    
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-18
          相关资源
          最近更新 更多