Gnana
Gnana

Reputation: 77

Switch between pie charts and bar chart in highcharts

I am searching for a feature that will allow me to switch from a pie chart to a bar chart (and back again) using the context menu provided by highcharts. The following image shows where I would like the chart switch to be placed.

enter image description here

This is what I have done so far:

Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: 'Browser market shares in January, 2018'
  },
  tooltip: {
    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: true,
        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    }
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
      name: 'Chrome',
      y: 61.41,
      sliced: true,
      selected: true
    }, {
      name: 'Internet Explorer',
      y: 11.84
    }, {
      name: 'Firefox',
      y: 10.85
    }, {
      name: 'Edge',
      y: 4.67
    }, {
      name: 'Safari',
      y: 4.18
    }, {
      name: 'Sogou Explorer',
      y: 1.64
    }, {
      name: 'Opera',
      y: 1.6
    }, {
      name: 'QQ',
      y: 1.2
    }, {
      name: 'Other',
      y: 2.61
    }]
  }]
});
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="http://code.highcharts.com/highcharts.js"></script>
  <script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>

<body>
  <div id="container" style="height: 400px; width: 800px"></div>

</body>

</html>

Upvotes: 1

Views: 1648

Answers (1)

ppotaczek
ppotaczek

Reputation: 39069

You can add a custom item to the exporting menu and in click event use update method for the chart with new options:

exporting: {
    menuItemDefinitions: {
        // Custom definition
        switchChart: {
            onclick: function() {
                var chartType = this.options.chart.type;

                this.update({
                    chart: {
                        type: chartType === 'bar' ? 'pie' : 'bar'
                    }
                })
            },
            text: 'Switch chart'
        }
    },
    buttons: {
        contextButton: {
            menuItems: ["switchChart", "separator", "printChart", "separator", "downloadPNG", "downloadJPEG", "downloadPDF", "downloadSVG"]
        }
    }
},

Live demo: http://jsfiddle.net/BlackLabel/xdsgL6rm/

API:

https://api.highcharts.com/highcharts/exporting.buttons.contextButton.menuItems

https://api.highcharts.com/class-reference/Highcharts.Chart#update

Upvotes: 1

Related Questions