Search code examples
chart.jsangular8ng2-charts

how to show bar graph on y axis in charjs


I am using ng2-charts which uses chartjs. Angular version is 8.2.14. I have to show bar graphs but they have to start from Y axis instead of X axis. Means Graphs should grow from y axis. What is the way to achieve this?


Solution

  • You will have to define the type of your Chart as horizontalBar in the configuration options:

    var myBarChart = new Chart(ctx, {
        type: 'horizontalBar',
        data: data,
        options: options
    });
    

    or TypeScript for ng2-charts:

    public barChartType: ChartType = 'horizontalBar';
    

    Bear in mind

    The configuration options for the horizontal bar chart are the same as for the bar chart.
    However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart.

    Here is an example on Stackblitz: https://stackblitz.com/edit/ng2-charts-bar-template-vqunbc

    export class AppComponent  {
      public barChartOptions: ChartOptions = {
        responsive: true,
      };
      public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
      public barChartType: ChartType = 'horizontalBar';
      public barChartLegend = true;
      public barChartPlugins = [];
    
      public barChartData: ChartDataSets[] = [
        { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
        { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' }
      ];
    
      constructor() { }
    
      ngOnInit() {
      }
    }
    

    See Chart.js documention for reference: https://www.chartjs.org/docs/latest/charts/bar.html#horizontal-bar-chart