sk

開発で得たこと

5分でRailsアプリにおしゃれでかっこいいグラフを実装。

f:id:sksksksksk:20170510232656p:plain

今回はおしゃれなグラフを作成します。

アニメーションがつき複数のグラフも作成することができます。

個人的にはChartkickよりもおすすめです。

しかも、実装が非常に簡単です。

ソースを読み込む JS

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

Jsのソースをいくつか読み込みます。

グラフを表示させる為のDIV

<div id="container" style="min-width: 400px; max-width: 600px; height: 400px; margin: 0 auto"></div>

divの間にチャートが表示されます。

チャートを生成するJS

Highcharts.chart('container', {
 
    chart: {
        polar: true,
        type: 'line'
    },
 
    title: {
        text: 'Budget vs spending',
        x: -80
    },
 
    pane: {
        size: '80%'
    },
 
    xAxis: {
        categories: ['Sales', 'Marketing', 'Development', 'Customer Support',
                'Information Technology', 'Administration'],
        tickmarkPlacement: 'on',
        lineWidth: 0
    },
 
    yAxis: {
        gridLineInterpolation: 'polygon',
        lineWidth: 0,
        min: 0

以上です。これだけで表示されます。

今回私が作ったものはこちらのコードです。

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
 
<div id="container" style="min-width: 400px; max-width: 600px; height: 400px; margin: 0 auto"></div>

<script>
Highcharts.chart('container', {

    chart: {
        polar: true,
        type: 'line'
    },

    title: {
        text: 'Budget vs spending',
        x: -80
    },

    pane: {
        size: '80%'
    },

    xAxis: {
        categories: ['Sales', 'Marketing', 'Development', 'Customer Support',
                'Information Technology', 'Administration'],
        tickmarkPlacement: 'on',
        lineWidth: 0
    },

    yAxis: {
        gridLineInterpolation: 'polygon',
        lineWidth: 0,
        min: 0
    },

    tooltip: {
        shared: true,
        pointFormat: '<span style="color:{series.color}">{series.name}: <b>${point.y:,.0f}</b><br/>'
    },

    legend: {
        align: 'right',
        verticalAlign: 'top',
        y: 70,
        layout: 'vertical'
    },

    series: [{
        name: 'Allocated Budget',
        data: [43000, 19000, 60000, 35000, 17000, 10000],
        pointPlacement: 'on'
    }, {
        name: 'Actual Spending',
        data: [50000, 39000, 42000, 31000, 26000, 14000],
        pointPlacement: 'on'
    }]

});
</script>


以上です。

ProgateやRailsチュートリアル、プログラミングスクールを通い終えたが現場のコードはかけない、

一体どうやって書くの?と思っているエンジニアのみなさんのためのチュートリアルを公開しています。

チュートリアル