Chartjs 2:chartjs中的多级/分层类别轴

时间:2017-10-27 14:10:03

标签: chart.js chart.js2

是否可以定义具有多级/类别轴的条形图?

例如,我想在此Excel图表中显示Region / Province类别: enter image description here

我找到了使用多个xAxes的this示例。

xAxes:[
    {
      id:'xAxis1',
      type:"category",
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          return month;
        }
      }
    },
    {
      id:'xAxis2',
      type:"category",
      gridLines: {
        drawOnChartArea: false, // only want the grid lines for one axis to show up
      },
      ticks:{
        callback:function(label){
          var month = label.split(";")[0];
          var year = label.split(";")[1];
          if(month === "February"){
            return year;
          }else{
            return "";
          }
        }
      }
    }
  ]

问题是两个轴似乎没有真正链接,第二轴的对齐是基于值而不是在较低级别类别的中间对齐。这种情况导致问题

在chart.js中有没有一种干净的方法来实现这一目标?

更新 我最终在chartjs上创建了feature request

4 个答案:

答案 0 :(得分:2)

您可以通过datesets为不同的轴单独提供值,并提供具有不同配置选项(borderColor, pointBackgroundColor, pointBorderColor)等的对象,我希望它能提供帮助。

这是带有更新的链接(你分享的小提琴)Updated Fiddle

data: {
labels: ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"],
datasets: [{
  label: '# of Votes',
  xAxisID:'xAxis1',
  data: [12, 19, 3, 5, 2, 3]
},

// here i added another data sets for xAxisID 2 and it works just fine
{
  label: '# of Potatoes',
  xAxisID:'xAxis2',
  data: [9, 17, 28, 26, 29, 9]
}]

}

我希望能解决你的问题:)

答案 1 :(得分:0)

希望这有帮助,

我做了一些研究,无法找到在chartjs中实现解决方案的方法。 Chartjs已经对条形图进行了分组,但没有像您的情况那样对子网格条形图进行分组。

Example: http://jsfiddle.net/harshakj89/ax3zxtzw/

以下是一些替代方案,

D3js(https://d3js.org/)可用于创建子分组条形图。可以从csv或json加载数据。 D3是高度可配置的,但你可能需要付出一些努力而不是chartjs。

https://plnkr.co/edit/qGZ1YuyFZnVtp04bqZki?p=preview
https://stackoverflow.com/questions/37690018/d3-nested-grouped-bar-chart
https://stackoverflow.com/questions/15764698/loading-d3-js-data-from-a-simple-json-string

ZingChart是一种商业工具,可用于实现带有子组合的条形图。

https://www.zingchart.com/docs/chart-types/bar-charts/

但我更喜欢D3而不是这个库。因为D3属于BSD许可证。

答案 2 :(得分:0)

答案 3 :(得分:0)

我发现拥有此功能的最佳库是Highcharts,这是我的实现: enter image description here 在这里http://jsfiddle.net/fieldsure/Lr5sjh5x/2/,您可以了解如何实现它。

$(function () {
    var chart = new Highcharts.Chart({
        chart: {
            renderTo: "container",
            type: "column",
            borderWidth: 5,
            borderColor: '#e8eaeb',
            borderRadius: 0,
            backgroundColor: '#f7f7f7'
        },
        title: {
            style: {
                'fontSize': '1em'
            },
            useHTML: true,
            x: -27,
            y: 8,
            text: '<span class="chart-title"> Grouped Categories with 2 Series<span class="chart-href"> <a href="http://www.blacklabel.pl/highcharts" target="_blank"> Black Label </a> </span> <span class="chart-subtitle">plugin by </span></span>'
        },
        yAxis: [{ // Primary yAxis
            labels: {
                format: '${value}',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            title: {
                text: 'Daily Tickets',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            }
        }, { // Secondary yAxis
            title: {
                text: 'Invoices',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            labels: {
                format: '${value}',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            opposite: true
        }]
        ,
        series: [{
            name: 'Daily',
            type: 'column',
            yAxis: 1,
            data: [4, 14, 18, 5, 6, 5, 14, 15, 18],
            tooltip: {
                valueSuffix: ' mm'
            }

        }, {
            name: 'Invoices',
            type: 'column',
            data: [4, 17, 18, 8, 9, 5, 13, 15, 18],
            tooltip: {
                valueSuffix: ' °C'
            }
        }],
        xAxis: {
            categories: [{
                name: "1/1/2014",
                categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
            }, {
                name: "1/2/2014",
                categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
            }, {
                name: "1/3/2014",
                categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
            }]
        }
    });
});
body {
    padding: 0px !important;
    margin: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://blacklabel.github.io/grouped_categories/grouped-categories.js"></script>

<div id="container" class="chart-container"></div>

但是问题是图书馆不是出于商业目的免费提供的,这是Chartjs implementation,在我看来,它是这样的:

const data ={"labels":[{"label":"Exams","children":["Wellness Examination"]},{"label":"Surgery","children":["Neuter Surgery"]},{"label":"Vaccines","children":["Bordetella"]},{"label":"Dentistry","children":["Dental Cleaning"]},{"label":"Diagnostics","children":["Other","Pre-Anesthetic","Adult Diagnostics","Pre-Anesthetic Diagnostics","Heartworm & Tick Borne Disease Test"]},{"label":"Treatments/Other","children":["Other","Microchip"]}],"datasets":[{"label":"Consumed","backgroundColor":"red","tree":[{"value":0,"children":["0"]},{"value":0,"children":["0"]},{"value":1,"children":["1"]},{"value":0,"children":["0"]},{"value":15,"children":["0","1","3","11","0"]},{"value":15,"children":["2","13"]}]},{"label":"Purchased","backgroundColor":"blue","tree":[{"value":28,"children":["28"]},{"value":1,"children":["1"]},{"value":24,"children":["24"]},{"value":10,"children":["10"]},{"value":103,"children":["2","16","34","49","2"]},{"value":165,"children":["75","90"]}]}]};
            window.onload = () => {
                const ctx = document.getElementById("canvas").getContext("2d");
                window.myBar = new Chart(ctx, {
                    type: 'bar',
                    data: data,
                    options: {
                        responsive: true,
                        title: {
                            display: true,
                            text: 'Chart.js Hierarchical Bar Chart'
                        },
                        layout: {
                            padding: {
                                // add more space at the bottom for the hierarchy
                                bottom: 45
                            }
                        },
                        scales: {
                            xAxes: [{
                                type: 'hierarchical',
                                stacked: false,
                                // offset settings, for centering the categorical
                                //axis in the bar chart case
                                offset: true,

                                // grid line settings
                                gridLines: {
                                    offsetGridLines: true
                                }
                            }],
                            yAxes: [{
                                stacked: false,
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                });

            };
canvas {
                        -moz-user-select: none;
                        -webkit-user-select: none;
                        -ms-user-select: none;
                    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/chart.js/dist/Chart.bundle.js"></script>
<script src="https://unpkg.com/chartjs-scale-hierarchical"></script>

        <div id="container" style="width: 75%;">
            <canvas id="canvas"></canvas>
        </div>
  

每增加一列,只需添加另一个数据集。