前提・実現したいこと
Chart.jsで棒グラフと折れ線グラフの複合グラフを作成したのですが、
折れ線グラフのみ、ツールチップを常時表示したいです。
よろしくお願いいたします。
発生している問題・エラーメッセージ
過去の質問を参考にしましたが、うまく表示できませんでした。
Chart.js 2.0 棒グラフに任意のTooltipを常時表示したい
リンク内容
該当のソースコード
html
1<div class="container" style="width:100%"> 2 <canvas id="myChart"></canvas> 3</div>
javascript
1<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script> 2<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.6.0/dist/chartjs-plugin-datalabels.min.js"></script> 3<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> 4 5<!-- Chart.js --> 6<script> 7window.onload = function() { 8 ctx = document.getElementById("myChart").getContext("2d"); 9 window.myBar = new Chart(ctx, { 10 type: 'bar', 11 data: barChartData, 12 options: complexChartOption, 13 }); 14}; 15 16// データ 17var barChartData = { 18 labels: ['2019年','2020年','2021年','2022年','2023年'], 19 datasets: [ 20 { 21 type: 'line', 22 label: '累計件数', 23 data: ['53.0','73.0','100.0','134.0','165.0'], 24 borderColor : "rgba(254,97,132,0.8)", 25 pointBackgroundColor : "rgba(254,97,132,0.8)", 26 fill: false, 27 yAxisID: "y-axis-1",// 追加 28 datalabels: {align: 'end'}, 29 }, 30 { 31 type: 'bar', 32 label: '発電量', 33 data: ['200.0','282.0','396.0','535.0','670.0'], 34 borderColor : "rgba(54,164,235,0.8)", 35 backgroundColor : "rgba(54,164,235,0.5)", 36 yAxisID: "y-axis-2", 37 }, 38 ], 39}; 40 41 42// Define a plugin to provide data labels 43Chart.plugins.register({ 44 afterDatasetsDraw: function (chart, easing, showAllTooltips) { 45 // To only draw at the end of animation, check for easing === 1 46 var ctx = chart.ctx; 47 48 chart.data.datasets.forEach(function (dataset, i) { 49 var meta = chart.getDatasetMeta(i); 50 if (!meta.hidden) { 51 meta.data.forEach(function (element, index) { 52 // Draw the text in black, with the specified font 53 ctx.fillStyle = 'rgb(0, 0, 0)'; 54 55 var fontSize = 18; 56 var fontStyle = 'normal'; 57 var fontFamily = 'Helvetica Neue'; 58 ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily); 59 60 // Just naively convert to string for now 61 var dataString = dataset.data[index].toString(); 62 63 // Make sure alignment settings are correct 64 ctx.textAlign = 'center'; 65 ctx.textBaseline = 'middle'; 66 67 var padding = 5; 68 var position = element.tooltipPosition(); 69 ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding); 70 }); 71 } 72 }); 73 } 74}); 75 76var complexChartOption = { 77 responsive: true, 78 scales: { 79 yAxes: [{ 80 id: "y-axis-1", 81 type: "linear", 82 position: "left", 83 ticks: { 84 max: 170.0, 85 min: 0, 86 stepSize: 10.0 87 }, 88 }, { 89 id: "y-axis-2", 90 type: "linear", 91 position: "right", 92 ticks: { 93 max: 700, 94 min: 0, 95 stepSize: 100.0 96 }, 97 gridLines: { 98 drawOnChartArea: false, 99 }, 100 }], 101 } 102}; 103</script>
試したこと
補足情報(FW/ツールのバージョンなど)
参考元のkei344さんの追記部分が無いようですが。これが肝だと思います。
あなたの回答
tips
プレビュー