求助:使用Highcharts与ECharts实现蝴蝶图绘制
蝴蝶图实现方案(无需Highcharts/ECharts)
下面是用原生HTML、CSS和JavaScript实现蝴蝶图的代码,完全不依赖Highcharts或ECharts,效果可以匹配你需要的样式:
完整代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>蝴蝶图</title> <style> .butterfly-chart { display: flex; align-items: center; justify-content: center; gap: 20px; padding: 20px; max-width: 800px; margin: 0 auto; } .chart-column { display: flex; flex-direction: column; gap: 10px; } .chart-item { display: flex; align-items: center; gap: 10px; height: 40px; } .left-bar { background-color: #4285F4; height: 100%; border-radius: 0 4px 4px 0; margin-right: 10px; } .right-bar { background-color: #EA4335; height: 100%; border-radius: 4px 0 0 4px; margin-left: 10px; } .value { font-size: 14px; color: #333; width: 40px; text-align: right; } .center-labels { display: flex; flex-direction: column; gap: 10px; } .center-label { height: 40px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px; width: 80px; } </style> </head> <body> <div class="butterfly-chart"> <div class="chart-column" id="leftChart"></div> <div class="center-labels"> <div class="center-label">儿童</div> <div class="center-label">青年</div> <div class="center-label">中年</div> <div class="center-label">老年</div> </div> <div class="chart-column" id="rightChart"></div> </div> <script> // 模拟数据,左侧为男性占比,右侧为女性占比 const chartData = [ { category: '儿童', male: 45, female: 55 }, { category: '青年', male: 52, female: 48 }, { category: '中年', male: 50, female: 50 }, { category: '老年', male: 40, female: 60 } ]; // 获取最大数值,用于计算柱状图宽度比例 const maxValue = Math.max(...chartData.flatMap(item => [item.male, item.female])); const barMaxWidth = 200; // 柱状图最大宽度(像素) // 生成左侧柱状图 const leftChart = document.getElementById('leftChart'); chartData.forEach(item => { const width = (item.male / maxValue) * barMaxWidth; const itemEl = document.createElement('div'); itemEl.className = 'chart-item'; itemEl.innerHTML = ` <span class="value">${item.male}%</span> <div class="left-bar" style="width: ${width}px"></div> `; leftChart.appendChild(itemEl); }); // 生成右侧柱状图 const rightChart = document.getElementById('rightChart'); chartData.forEach(item => { const width = (item.female / maxValue) * barMaxWidth; const itemEl = document.createElement('div'); itemEl.className = 'chart-item'; itemEl.innerHTML = ` <div class="right-bar" style="width: ${width}px"></div> <span class="value">${item.female}%</span> `; rightChart.appendChild(itemEl); }); </script> </body> </html>
关键说明
- 布局逻辑:通过Flex布局实现左右两列柱状图与中间分类标签的对称排列,还原蝴蝶图的核心视觉形态。
- 数据适配:基于数据中的最大值计算柱子宽度比例,确保不同数值的柱子按比例缩放,保持视觉一致性。
- 样式自定义:可直接修改CSS中的颜色、圆角、尺寸等属性,快速匹配目标图的样式风格。
- 扩展性:新增分类或调整数据只需修改
chartData数组,代码会自动生成对应柱状图。
内容的提问来源于stack exchange,提问作者Dharmarajan
相关产品推荐
相关产品推荐

