メインコンテンツへスキップ
見出し画像

教室アプリ11:帯グラフ


    画像

    タイトル、項目名、数値を入力し、好きな色を選んでください。**「グラフを更新」を押すと、即座に帯グラフが完成します。10%未満の項目は自動で整理され、見やすくなります。完成後は「画像で保存」**しましょう。

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>教室アプリ11:帯グラフ</title>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
        <style>
            body { 
                font-family: 'Helvetica Neue', Arial, sans-serif; 
                margin: 0; 
                padding: 20px; 
                background-color: #f0f2f5; 
                display: flex;
                justify-content: center;
            }
            .container {
                max-width: 900px;
                width: 100%;
                display: flex;
                flex-direction: column;
                gap: 20px;
            }
            .input-panel {
                background: white;
                padding: 25px;
                border-radius: 15px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            }
            .display-panel {
                background: white;
                padding: 20px;
                border-radius: 15px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                height: 450px; 
                display: flex;
                flex-direction: column;
                justify-content: center;
            }
            .row { margin: 8px 0; display: flex; align-items: center; gap: 10px; }
            #chartTitleInput { 
                width: 100%; font-size: 20px; padding: 12px; border: 2px solid #1a1a1a; 
                border-radius: 5px; margin-bottom: 15px; box-sizing: border-box;
            }
            input[type="text"] { flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 5px; }
            input[type="number"] { width: 65px; padding: 8px; border: 1px solid #ddd; border-radius: 5px; }
            input[type="color"] { width: 35px; height: 35px; border: none; cursor: pointer; background: none; }
            
            .btn-group { margin-top: 15px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
            button { padding: 14px; cursor: pointer; border: none; border-radius: 8px; font-size: 16px; font-weight: bold; transition: 0.3s; }
            .btn-draw { background: #1a1a1a; color: white; }
            .btn-save { background: #27ae60; color: white; }
            button:hover { opacity: 0.8; }
    
            .canvas-container { 
                width: 100%; 
                height: 300px; 
                position: relative; 
            }
        </style>
    </head>
    <body>
    
        <div class="container">
            <div class="input-panel">
                <input type="text" id="chartTitleInput" placeholder="グラフのタイトルを入力" value="好きな給食">
                <div id="inputRows">
                    <div class="row">1. <input type="text" id="label1" value="カレーライス"> <input type="number" id="data1" value="120"> <input type="color" id="color1" value="#ff6384"></div>
                    <div class="row">2. <input type="text" id="label2" value="ハヤシライス"> <input type="number" id="data2" value="100"> <input type="color" id="color2" value="#36a2eb"></div>
                    <div class="row">3. <input type="text" id="label3" value="クリームシチュー"> <input type="number" id="data3" value="85"> <input type="color" id="color3" value="#ffce56"></div>
                    <div class="row">4. <input type="text" id="label4" value="オムライス"> <input type="number" id="data4" value="55"> <input type="color" id="color4" value="#4bc0c0"></div>
                    <div class="row">5. <input type="text" id="label5" value="ハンバーグ"> <input type="number" id="data5" value="30"> <input type="color" id="color5" value="#9966ff"></div>
                    <div class="row">6. <input type="text" id="label6" value="その他"> <input type="number" id="data6" value="40"> <input type="color" id="color6" value="#ff9f40"></div>
                </div>
                <div class="btn-group">
                    <button class="btn-draw" onclick="updateGraph()">グラフを更新</button>
                    <button class="btn-save" onclick="saveGraph()">画像で保存</button>
                </div>
            </div>
    
            <div class="display-panel">
                <div class="canvas-container">
                    <canvas id="myChart"></canvas>
                </div>
            </div>
        </div>
    
        <script>
            let myChart = null;
            if (typeof ChartDataLabels !== 'undefined') { Chart.register(ChartDataLabels); }
    
            function updateGraph() {
                const titleInput = document.getElementById('chartTitleInput').value;
                const dataValues = [];
                for (let i = 1; i <= 6; i++) {
                    dataValues.push(Number(document.getElementById('data' + i).value));
                }
                const total = dataValues.reduce((a, b) => a + b, 0);
    
                const datasets = [];
                for (let i = 1; i <= 6; i++) {
                    const val = dataValues[i-1];
                    const label = document.getElementById('label' + i).value;
                    const color = document.getElementById('color' + i).value;
                    const pct = total > 0 ? (val * 100 / total) : 0;
    
                    datasets.push({
                        label: label,
                        data: [val],
                        backgroundColor: color,
                        borderWidth: 2,
                        borderColor: '#ffffff',
                        percentage: pct,
                        barPercentage: 1.0,
                        categoryPercentage: 1.0
                    });
                }
    
                if (myChart) { myChart.destroy(); }
    
                const ctx = document.getElementById('myChart').getContext('2d');
                myChart = new Chart(ctx, {
                    type: 'bar',
                    data: { labels: [''], datasets: datasets },
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: false,
                        layout: { padding: { top: 100, bottom: 20 } }, 
                        scales: {
                            x: { stacked: true, display: false, max: total },
                            y: { stacked: true, display: false }
                        },
                        plugins: {
                            title: { 
                                display: true, text: titleInput, 
                                font: { size: 24, weight: 'bold' }, padding: { bottom: 20 }
                            },
                            legend: { display: false },
                            datalabels: {
                                color: (context) => context.dataset.percentage >= 10 ? '#ffffff' : '#000000',
                                font: { weight: 'bold', size: 14 },
                                formatter: (value, context) => {
                                    if (value <= 0) return null;
                                    const label = context.dataset.label;
                                    const pct = context.dataset.percentage.toFixed(0) + "%";
                                    
                                    // 10%以上の時:項目名 + 数値をグラフ内に
                                    if (context.dataset.percentage >= 10) {
                                        return label + "\n" + pct;
                                    }
                                    // 10%未満の時:数値のみをグラフ内に(項目名は後述のanchorで調整)
                                    return pct;
                                },
                                // 表示位置の制御
                                anchor: 'center',
                                align: 'center',
                                
                                // 10%未満の項目名だけを外に出すための「もう一つのラベル」的な表現はChart.js単体では難しいため、
                                // datalabelsの複数設定(配列)を使用して、項目名を外に飛ばします。
                            }
                        }
                    },
                    // 10%未満のラベル(項目名)を上に出すための追加設定
                    plugins: [{
                        id: 'extraLabels',
                        afterDraw: (chart) => {
                            const ctx = chart.ctx;
                            chart.data.datasets.forEach((dataset, i) => {
                                if (dataset.percentage < 10 && dataset.data[0] > 0) {
                                    const meta = chart.getDatasetMeta(i);
                                    const model = meta.data[0];
                                    const x = (model.x + model.base) / 2;
                                    const y = model.y - 60; // グラフの上方に表示
    
                                    ctx.save();
                                    ctx.fillStyle = '#000000';
                                    ctx.font = 'bold 14px Helvetica Neue';
                                    ctx.textAlign = 'center';
                                    ctx.fillText(dataset.label, x, y);
                                    ctx.restore();
                                }
                            });
                        }
                    }]
                });
            }
    
            function saveGraph() {
                if (!myChart) return;
                const canvas = document.getElementById('myChart');
                const link = document.createElement('a');
                link.href = canvas.toDataURL('image/png');
                link.download = '帯グラフ_最適化版.png';
                link.click();
            }
    
            window.onload = updateGraph;
        </script>
    </body>
    </html>
     
     
    小学校教師/教職30年/小学校の教室で使うアプリをAIで作っています

    あなたへのおすすめ