Chart.js从右到左显示x轴数据 [英] Chart.js show x-axis data from right to left

查看:54
本文介绍了Chart.js从右到左显示x轴数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究chart.js垂直图表,并且希望对其显示方式进行一些更改.

基本上,第一个数据将从左显示,但我想从右显示第一个数据.有可能吗?

这是我到目前为止所拥有的工作版本:

https://jsfiddle.net/wxaL6en0/4/

 选项:{响应式的:是的,maintenanceAspectRatio:否,传奇: {显示:false,}} 

这就是我为该选项所做的事情.

我期望的结果是, April 位于右侧,而第一个栏显示在右侧.

我不确定这是否可行,因为我没有在互联网上找到任何解决方案.但我希望有人尝试过.

解决方案

不幸的是,似乎 Chart.js 2.8.0仅对yAxes的ticks对象支持反向布尔参数.

这意味着,没有黑客或猴子补丁,就不能在Chart.js API中完成.

我想出的这个肮脏的解决方案似乎是过度设计的,因为仅通过按索引引用引用data.data数组项来更改它不会适当地触发Chart.js动画,因此需要使用拼接./p>

说明:

实际上,这个想法很简单:

为了从右到左显示先验已知数量的小条
首先需要创建一个长度等于条形数量的数组,并用空值填充它.
换句话说,一个包含的空值与要显示的条数一样多的数组.

然后每个新值都必须从第一个索引(数组的末尾)的右边(数组的末尾)插入(在该索引下),数组项为null或仅在正确的索引处,从array.length倒数到1.0.

可视化":

 让value = 1;const graphData = Array(3).fill(null);console.log(graphData)for(让我= graphData.length-1;我> = 0; --i){graphData.splice(i,1,value ++);console.log(graphData)}  

示例:

  class GraphController {大小= 0;数据= [];标签= [];graphData = [];ctx = null;chart = null;构造函数(大小,数据,标签,canvasId){this.size =大小;this.data =数据;this.labels =标签;this.ctx = document.getElementById(canvasId).getContext('2d');this.graphData = Array(size).fill(null);}fetchAndDraw(index = 1){const item = this.data [index-1];如果(item.TotalReward){this.graphData [this.size-index] = item.TotalReward;}if(索引> 1&&< this.size){this.chart.data.datasets [0] .data.splice(this.size-index,1,item.TotalReward);this.chart.update();} 别的 {如果(this.chart){this.chart.destroy();}this.chart = new Chart(this.ctx,{类型:酒吧",数据: {标签:this.labels,数据集:[{数据:[... this.graphData],backgroundColor:#fff",hoverBackgroundColor:'#d5d5d5',borderWidth:0}]},选项: {响应式的:是的,maintenanceAspectRatio:否,传奇: {显示:false,},标题: {显示:false,},工具提示:{已启用:false,},比例尺:{x轴:[{barPercentage:1.0,类别百分比:0.55,网格线: {显示:false,颜色:#fff",drawBorder:否,zeroLineColor:#fff"},滴答声:{fontFamily:'"Avenir Next","Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"',字号:16fontColor:'#fff',内边距:15,}}],y轴:[{类别百分比:0.8,bar百分比:0.8,网格线: {显示:false,颜色:#fff",drawBorder:否,zeroLineColor:#fff"},滴答声:{最小值:0,stepSize:10,fontFamily:'"Avenir Next","Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"',字号:16fontColor:'#fff',填充:10,回调:函数(值){返回'$'+值;}}}],},},});}索引++;if(index< = this.size){setTimeout(()=> {this.fetchAndDraw(index);},1000);}}}const data = [{月":"4月18日",总奖励":10.37},{月":"18年5月",总奖励":18.11},{月":"6月18日",总奖励":25.49},{"Month":"January","TotalReward":35.55},{月":"2月",总奖励":50.25},{月":"3月",总奖励":59.15},]const rewardLabels = [" 4月18日," 5月18日," 6月18日," 1月," 2月," 3月] .reverse();const graph = new GraphController(6,data,rewardLabels,'rewardChart');graph.fetchAndDraw();  

  .chart-wrap {背景:#333;内边距:20px 10px;}  

 < link href ="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"rel =" stylesheet"/>< script src ="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>< script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>< div class ="chart-wrap">< canvas id ="rewardChart" width ="600" height ="165"></canvas></div>  

I am working on the chart.js vertical chart and I want to make a slight change in the way it displays.

Basically the first data will be displayed from the left but I want to display first data from right. Is that possible?

Here is the working version of what I have so far:

https://jsfiddle.net/wxaL6en0/4/

   options: {

      responsive: true,
      maintainAspectRatio: false,

      legend: {
        display: false,
      }
   }

This is what i have done for the option.

The result I am expecting is, April to be on the right and first bar to display on the right.

I am not sure this is possible since I didn't find any solution over the internet. But I hope someone tried this before.

解决方案

Unfortunately it seems that Chart.js 2.8.0 supports reverse boolean parameter only for ticks object of yAxes.

This means, that without hacking or monkey patching it cannot be done within Chart.js API.

Also this dirty solution I came up with seems to be over-engineered, because simply changing dataset.data array item by referring to it by its index does not trigger Chart.js animations properly, therefore one needs to use splice.

Explanation:

Actually the idea is pretty simple:

In order to show bars from right to left for a priori known number of them
One needs to first create an array of length equal to number of bars and fill it with nulls.
In other words an array containing as many nulls as there are bars to be displayed.

Then each new value has to be inserted (using splice) from the right (end of the array) at first index under which array item is null or just simply at correct index, counting down from the array.length - 1 to 0.

"Visualisation":

let value = 1;

const graphData = Array(3).fill(null);
console.log(graphData)

for(let i = graphData.length - 1; i >= 0; --i){
    graphData.splice(i, 1, value++);
    console.log(graphData)
}

Example:

class GraphController {
    size = 0;
    data = [];
    labels = [];
    graphData = [];
    ctx = null;
    chart = null;

    constructor(size, data, labels, canvasId) {
        this.size = size;
        this.data = data;
        this.labels = labels;

        this.ctx = document.getElementById(canvasId).getContext('2d');

        this.graphData = Array(size).fill(null);
    }

    fetchAndDraw(index = 1) {
        const item = this.data[index - 1];
        if (item.TotalReward) {
            this.graphData[this.size - index] = item.TotalReward;
        }

        if (index > 1 && index < this.size) {
            this.chart.data.datasets[0].data.splice(this.size - index, 1, item.TotalReward);
            this.chart.update();
        } else {
            if (this.chart) {
                this.chart.destroy();
            }

            this.chart = new Chart(this.ctx, {
                type: 'bar',
                data: {
                    labels: this.labels,
                    datasets: [{
                        data: [...this.graphData],
                        backgroundColor: '#fff',
                        hoverBackgroundColor: '#d5d5d5',
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    legend: {
                        display: false,
                    },
                    title: {
                        display: false,
                    },
                    tooltips: {
                        enabled: false,
                    },
                    scales: {
                        xAxes: [{
                            barPercentage: 1.0,
                            categoryPercentage: 0.55,
                            gridLines: {
                                display: false,
                                color: '#fff',
                                drawBorder: false,
                                zeroLineColor: '#fff'
                            },
                            ticks: {
                                fontFamily: '"Avenir Next", "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
                                fontSize: 16,
                                fontColor: '#fff',
                                padding: 15,
                            }
                        }],
                        yAxes: [{
                            categoryPercentage: 0.8,
                            barPercentage: 0.8,
                            gridLines: {
                                display: false,
                                color: '#fff',
                                drawBorder: false,
                                zeroLineColor: '#fff'
                            },
                            ticks: {
                                min: 0,
                                stepSize: 10,
                                fontFamily: '"Avenir Next", "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
                                fontSize: 16,
                                fontColor: '#fff',
                                padding: 10,
                                callback: function (value) {
                                    return '$' + value;
                                }
                            }
                        }],
                    },
                },
            });
        }

        index++;
        if (index <= this.size) {
            setTimeout(() => {
                this.fetchAndDraw(index);
            }, 1000);
        }
    }
}



const data = [
    { "Month": "April ‘18", "TotalReward": 10.37 },
    { "Month": "May ‘18", "TotalReward": 18.11 },
    { "Month": "June ‘18", "TotalReward": 25.49 },
    { "Month": "January", "TotalReward": 35.55 },
    { "Month": "February", "TotalReward": 50.25 },
    { "Month": "March", "TotalReward": 59.15 },
]

const rewardLabels = ["April ‘18", "May ‘18", "June ‘18", "January", "February", "March"].reverse();

const graph = new GraphController(6, data, rewardLabels, 'rewardChart');
graph.fetchAndDraw();

.chart-wrap {
  background: #333;
  padding: 20px 10px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chart-wrap">
  <canvas id="rewardChart" width="600" height="165"></canvas>
</div>

这篇关于Chart.js从右到左显示x轴数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆