Chart.js 多轴混合图表:实现柱状图与折线图的左右Y轴标签显示

Chart.js 多轴混合图表:实现柱状图与折线图的左右Y轴标签显示 Chart.<span class="wpcom_tag_link"><a href="https://www.chuangxiangniao.com/p/tag/js" title="js" target="_blank">js</a></span> 多轴混合图表示例 canvas { -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; }

// 自定义斜线图案背景函数 function createDiagonalPattern(color = ‘black’) { let shape = document.createElement(‘canvas’); shape.width = 10; shape.height = 10; let c = shape.getContext(‘2d’); c.strokeStyle = color; c.beginPath(); c.moveTo(2, 0); c.lineTo(10, 8); c.stroke(); c.beginPath(); c.moveTo(0, 8); c.lineTo(2, 10); c.stroke(); return c.createPattern(shape, ‘repeat’); } var barChartData = { labels: [“January”, “February”, “March”, “April”, “May”, “June”, “July”], datasets: [{ type: ‘bar’, // 柱状图类型 label: “Visitor”, // 访客数 data: [200, 185, 590, 621, 250, 400, 95], fill: false, backgroundColor: createDiagonalPattern(‘grey’), borderColor: ‘grey’, borderWidth: 1, hoverBackgroundColor: ‘#71B37C’, hoverBorderColor: ‘#71B37C’, yAxisID: ‘y-axis-1’ // 关联到左侧Y轴 }, { type: ‘line’, // 折线图类型 label: “Sales”, // 销售额 data: [51, 65, 40, 49, 60, 37, 40], fill: false, borderColor: ‘#2E41CF’, backgroundColor: ‘#2E41CF’, pointBorderColor: ‘#2E41CF’, pointBackgroundColor: ‘white’, pointHoverBackgroundColor: ‘#2E41CF’, pointHoverBorderColor: ‘#2E41CF’, pointStyle: ‘circle’, pointRadius: 10, pointHoverRadius: 15, pointBorderWidth: 3, yAxisID: ‘y-axis-2’ // 关联到右侧Y轴 }] }; window.onload = function() { var ctx = document.getElementById(“canvas”).getContext(“2d”); window.myBar = new Chart(ctx, { type: ‘bar’, // 默认图表类型,但数据集中的type会覆盖 data: barChartData, options: { responsive: true, tooltips: { mode: ‘index’, // 提示框模式,显示所有数据集信息 intersect: false, // 鼠标不需精确覆盖到元素 }, elements: { line: { fill: false // 折线图不填充区域 } }, scales: { xAxes: [{ // X轴配置 display: true, // 显示X轴 gridLines: { display: true // 显示X轴网格线 }, ticks: { display: true // 显示X轴刻度标签 } }], yAxes: [{ // 左侧Y轴 (访客数) type: “linear”, display: true, // !!! 关键:设置为 true 以显示轴和标签 position: “left”, id: “y-axis-1”, // 与 Visitor 数据集的 yAxisID 匹配 gridLines: { display: true // 显示

以上就是Chart.js 多轴混合图表:实现柱状图与折线图的左右Y轴标签显示的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1537727.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月21日 04:23:05
下一篇 2025年12月21日 04:23:11

相关推荐

发表回复

登录后才能评论
关注微信