Document

初めに

棒グラフを横に倒した横棒グラフ。英語の方がカッコいい。horizontal bar chart。横に倒すか、倒さないかの判断基準は、グループの項目が多いかどうかだと思います。項目が多いと、横に倒すのがいいのではないかと思います。項目が少ない場合には、横長のグラフになるので差を強調(印象操作)したいときに使えると思います。

コード

javascriptのライブラリであるchartjsを使用します。1つのhtmlファイルを作成し、ブラウザで読み込んでください。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        #canvasdiv {
            height: auto;
            margin: 10px 50px 50px 50px;
        }
    </style>
</head>

<body>
    <div id="canvasdiv">
        <canvas id="myChart" width="200" height="100"></canvas>
    </div>
    <script>

        Chart.defaults.font.size = 18;
        Chart.defaults.animation.duration = 2500

        var ctx = document.getElementById('myChart');

        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                datasets: [{
                    label: "",
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: 'y',
                plugins: {
                    title: {
                        display: true,
                        text: 'グループ別のコスト'
                    },
                    legend: { display: false },
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'グループ',
                            color: 'grey',
                        },
                    },
                    x: {
                        title: {
                            display: true,
                            text: '売上',
                            color: 'grey',
                        },
                    }
                }
            }
        });

    </script>

</body>

</html>
category