LoginSignup
0
2

More than 5 years have passed since last update.

HighChartsのY軸を動的に変える方法

Last updated at Posted at 2018-04-20

経緯

HighChartsで積み上げ棒グラフを作るとき、構成比率の推移を見たいときと、値の大きさの変化をみたいときがあるかと思います。

そんなとき2種類のグラフを作るのは面倒です。
なので、ボタン一つで、Y軸を値と比率に変えられないかと思いました。

サンプルコード

<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-type" content="text/css" />
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function () {
    var sample = Highcharts.chart('sample', {
        chart: {type: 'column',zoomType: 'xy'},
        time: {timezone: 'Asia/Tokyo'},
        xAxis: {type: 'datetime',dateTimeLabelFormats: {month:'%Y'}},
        yAxis: {title: {enabled: false}},
        legend: {align: 'left',verticalAlign: 'top',},
        plotOptions: {column: {stacking: 'normal'}},
        title: {useHTML: true,text: 'サンプル',style: {fontWeight: 'bold',color :'black',fontSize: 12}},
        series: [
            { name: '男性',
              color: 'rgba(0, 0, 255, 0.5)',
              data: [[Date.parse('2017-01-01'),400],[Date.parse('2018-01-01'),500]]
              },
            { name: '女性',
              color: 'rgba(255, 0, 0, 0.5)',
              data: [[Date.parse('2017-01-01'),500],[Date.parse('2018-01-01'),700]]
            }
        ]
    });
    $('#sample_cum').click(function () {
        sample.update({plotOptions: {column: {stacking: 'normal'}}});
    });
    $('#sample_pct').click(function () {
        sample.update({plotOptions: {column: {stacking: 'percent'}}});
    });
});
</script>
</head> 
<body>
<div>
    <div id='sample'></div><button id="sample_cum">積み上げ</button>&nbsp;<button id="sample_pct">比率</button>
</div>
</body>
</html>

動的にY軸を変えているのはこちらの部分となります。

$('#sample_cum').click(function () {
    sample.update({plotOptions: {column: {stacking: 'normal'}}});
});
$('#sample_pct').click(function () {
    sample.update({plotOptions: {column: {stacking: 'percent'}}});
});

グラフ要素に対する「update」という命令で、構成要素の内容を変える、という設定を書いておきます。

余談:他の要素もupdateできそうですね。

グラフエリアに対して「update」をかけられるので、ここで指定したplotOptions以外にも、さまざまな要素がupdateできそうです。
おいおい試してみます。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2