Highcharts条形:分类比较、累计与负值
用实际水平柱体理解bar、堆叠及正负方向。
学完这一章,你能够
- 用实际水平柱体理解bar、堆叠及正负方向。
- 条形、分类和标签
分类和值的方向
bar使分类轴竖直、数值轴水平;column则通常分类水平、数值竖直。基本条形、累计和负值分别对应不同配置,反向数值不是reversed分类逆序。
本章三条五分类系列有独立入口与操作,图例、标签及单位与当前数据一致。堆叠需要同分类同组对应,占比要标注分母,未知值不能静默改成零。
空间和读取
groupPadding影响类别组间留白,pointPadding影响组内柱体留白,grouping:false会改变自动布局;minPointLength可让小值可见,但不改变原数据。
横向标签长、浮动图例及窗口宽度会影响可读性。以实际坐标和数值核对正负与分组,不只看颜色;本轮电脑端实例不代表移动端已经验收。
条形、分类和标签
bar把分类放在垂直方向、数值放在水平方向。三条五分类系列、单位后缀和数据标签分别配置;浮动图例仍须保留可读位置。
图表外框、绘图区和图例是不同区域。数据标签可因碰撞隐藏,不能只按标签节点数证明所有文字都可见;值、长度及坐标应一起核对。
本站本例完成对应操作后的实际截图,与本例代码和状态绑定,不计为来源原图。
条形堆叠的三种状态
series.stacking:normal可用于条形累计;percent显示占比;null取消累计。系列间同分类对应关系不能靠数组长度推断。
分别点击三个按钮核对总量、百分比之和与取消状态。图例隐藏系列会影响可见组成,报表应解释分母和单位而不是只换图形。
本站本例完成对应操作后的实际截图,与本例代码和状态绑定,不计为来源原图。
负值条形
负y在水平数值轴相对零向另一侧延伸;这不是设置reversed,也不是将分类逆序。保留三条系列中的负数及其分类。
比较负点与零基线的实际坐标。负数不适合强制yAxis.min:0,否则会裁掉内容;同样不能把负贡献当作正数堆叠。
本站本例完成对应操作后的实际截图,与本例代码和状态绑定,不计为来源原图。
运行代码文件:columns.js
下列代码与本章独立工程实际脚本一致;容器、本地数据和模块随工程包保留。
"use strict";
window.mbskyErrors=[];window.addEventListener("error",e=>mbskyErrors.push(e.message));window.addEventListener("unhandledrejection",e=>mbskyErrors.push(String(e.reason)));
const plots={},names=["HTML5","CSS","JavaScript"],cats=["一","二","三","四","五"];
const base={chart:{animation:false},title:{text:"蓝色天空网 · mbsky.com"},subtitle:{text:"本站虚构练习数据"},plotOptions:{series:{animation:false}},colors:["#2563eb","#f97316","#10b981","#8b5cf6"],accessibility:{enabled:true}};
function make(id,options){return plots[id]=Highcharts.chart(id,Highcharts.merge(base,options));}
function series(negative=false){return names.map((name,i)=>({name,data:negative?[[5,3,4,7,2],[2,-2,-3,2,1],[3,4,4,-2,5]][i]:[[5,3,4,7,2],[2,2,3,2,1],[3,4,4,2,5]][i]}));}
make("bar",{chart:{type:"bar"},xAxis:{categories:cats,title:{text:null}},yAxis:{min:0,title:{text:"虚构练习次数",align:"high"}},tooltip:{valueSuffix:" 次"},plotOptions:{bar:{dataLabels:{enabled:true}}},legend:{layout:"vertical",align:"right",verticalAlign:"top",x:-20,y:80,floating:true,borderWidth:1,backgroundColor:"#fff",shadow:true},series:series()});
make("bar-stacked",{chart:{type:"bar"},xAxis:{categories:cats},yAxis:{min:0,title:{text:"虚构练习次数"}},plotOptions:{series:{stacking:"normal"},bar:{dataLabels:{enabled:true}}},series:series()});
for(const [id,mode]of [["percent","percent"],["none",null],["normal","normal"]])document.querySelector(`#bar-${id}`).onclick=()=>{plots["bar-stacked"].series.forEach(s=>s.update({stacking:mode},false));plots["bar-stacked"].redraw();};
for(const type of ["bar","column"])make(type+"-negative",{chart:{type},xAxis:{categories:cats},yAxis:{title:{text:"计划偏差"},plotLines:[{value:0,width:1,color:"#475569"}]},series:series(true)});
make("column",{chart:{type:"column"},xAxis:{categories:Array.from({length:12},(_,i)=>`${i+1}月`),crosshair:true},yAxis:{min:0,title:{text:"虚构练习次数"}},tooltip:{headerFormat:'<span>{point.key}</span><table>',pointFormat:'<tr><td>{series.name}</td><td><b>{point.y:.1f} 次</b></td></tr>',footerFormat:'</table>',shared:true,useHTML:true},plotOptions:{column:{pointPadding:.2,borderWidth:0}},series:[...names,"综合"].map((name,i)=>({name,data:Array.from({length:12},(_,j)=>10+(i+1)*j)}))});
make("column-stacked",{chart:{type:"column"},xAxis:{categories:cats},yAxis:{min:0,title:{text:"练习总量"},stackLabels:{enabled:true,style:{fontWeight:"bold",color:"#526078"}}},tooltip:{formatter(){return `${this.series.name}:${this.y};本分类总量:${this.total}`;}},plotOptions:{column:{stacking:"normal",dataLabels:{enabled:true,color:"white",style:{textOutline:"1px black"}}}},series:series()});
make("grouped",{chart:{type:"column"},xAxis:{categories:cats},yAxis:{min:0,allowDecimals:false,title:{text:"独立组练习总量"}},plotOptions:{column:{stacking:"normal"}},series:[{name:"甲一",stack:"甲",data:[5,3,4,7,2]},{name:"甲二",stack:"甲",data:[3,4,4,2,5]},{name:"乙一",stack:"乙",data:[2,5,6,2,1]},{name:"乙二",stack:"乙",data:[3,0,4,4,3]}]});
make("percent",{chart:{type:"column"},xAxis:{categories:cats},yAxis:{min:0,title:{text:"练习组成 / %"}},tooltip:{shared:true,pointFormat:'{series.name}:{point.y} 次({point.percentage:.1f}%)<br>'},plotOptions:{column:{stacking:"percent"}},series:series()});
make("rotated",{chart:{type:"column"},xAxis:{type:"category",labels:{rotation:-45,style:{fontSize:"13px",fontFamily:"system-ui"}}},yAxis:{min:0,title:{text:"虚构练习量"}},legend:{enabled:false},tooltip:{pointFormat:"本站练习:{point.y:.1f} 次"},series:[{name:"练习组",data:Array.from({length:20},(_,i)=>[`练习组${i+1}`,30-i*.7]),dataLabels:{enabled:true,rotation:-90,color:"white",align:"right",format:"{point.y:.1f}",y:10,style:{fontSize:"13px",textOutline:"none"}}}]});
function aggregate(rows){const groups=new Map();for(const row of rows){const match=row.trim().match(/^(.+?)\s+(\d+(?:\.\d+)?)$/);if(!match)throw new TypeError("练习明细需要名称和非负有限数值");const full=match[1],value=Number(match[2]),brand=names.find(name=>full.startsWith(name+" "))||"其他";const version=brand==="其他"?full:full.slice(brand.length).trim();if(!Number.isFinite(value))throw new TypeError("非有限数值");if(!groups.has(brand))groups.set(brand,[]);groups.get(brand).push([version,value]);}return [...groups].map(([name,data])=>({name,total:data.reduce((n,q)=>n+q[1],0),data:data.sort((a,b)=>b[1]-a[1])})).sort((a,b)=>b.total-a.total);}
const groups=aggregate(["HTML5 结构 12","HTML5 表单 8","CSS 布局 9","CSS 选择器 6","JavaScript 异步 7","JavaScript DOM 3","自定义组件 2"]);
make("drilldown",{chart:{type:"column"},xAxis:{type:"category"},yAxis:{min:0,title:{text:"虚构练习次数"}},legend:{enabled:false},series:[{name:"课程汇总",colorByPoint:true,data:[...groups.map(g=>({name:g.name,y:g.total,drilldown:g.name})),{name:"不可下钻示意",y:1,drilldown:null}]}],drilldown:{animation:false,breadcrumbs:{position:{align:"right"}},series:[...groups.map(g=>({id:g.name,name:g.name+"明细",type:"column",data:g.data.map(([name,y])=>({name,y,drilldown:g.name==="HTML5"&&name==="结构"?"structure-detail":null}))})),{id:"structure-detail",name:"结构细分",type:"column",data:[["语义元素",7],["文档结构",5]]}]}});
document.querySelector("#up").onclick=()=>plots.drilldown.drillUp();
make("fixed",{chart:{type:"column"},xAxis:{categories:["甲组","乙组","丙组"]},yAxis:[{min:0,title:{text:"练习次数"}},{title:{text:"学习分钟"},opposite:true}],tooltip:{shared:true},plotOptions:{column:{grouping:false,borderWidth:0,shadow:false}},series:[{name:"次数计划",data:[150,73,20],pointPadding:.3,pointPlacement:-.2},{name:"次数实际",data:[140,90,40],pointPadding:.4,pointPlacement:-.2},{name:"时间计划",data:[183.6,178.8,198.5],pointPadding:.3,pointPlacement:.2,yAxis:1,tooltip:{valueSuffix:" 分钟"}},{name:"时间实际",data:[203.6,198.8,208.5],pointPadding:.4,pointPlacement:.2,yAxis:1,tooltip:{valueSuffix:" 分钟"}}]});
document.querySelector("#padding").onclick=()=>{const s=plots.fixed.series[1];s.update({pointPadding:s.options.pointPadding===.4?.25:.4});};
function tableChart(endRow){if(plots.table)plots.table.destroy();make("table",{chart:{type:"column"},data:{table:"learning-table",...(endRow===undefined?{}:{startRow:0,endRow,startColumn:0,endColumn:2})},yAxis:{allowDecimals:false,title:{text:"虚构练习次数"}},tooltip:{formatter(){return `${this.series.name} · ${this.name}:${this.y} 次`;}}});}
document.querySelector("#table-update").onclick=()=>{document.querySelector("#learning-table tbody tr td").textContent="9";tableChart();};document.querySelector("#table-slice").onclick=()=>tableChart(2);tableChart();
window.mbskyColumns={plots,groups,aggregate,tableChart};
本章配置与条件
| 配置或接口 | 类型/写法 | 用途与准确条件 | 本例或迁移说明 |
| groupPadding / pointPadding | number | 分类组与组内留白 | 不是固定像素 |
| stacking / stack | 累计模式 / 组标识 | 同组同分类累计 | 百分比原值保留 |
| dataLabels.enabled / minPointLength | boolean / number | 标签与最小视觉长度 | 不能改变真实y |
本章独立核心源码与验证步骤
展开查看收起
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="robots" content="noindex,nofollow"><title>条形、分类和标签 | 蓝色天空网 mbsky.com</title><link rel="stylesheet" href="../bootstrap.css"><script defer src="../lesson-view.js"></script></head><body data-section="case-bar" data-mode=""><header>蓝色天空网 · mbsky.com</header><main><h1>条形、分类和标签</h1><p>bar把分类放在垂直方向、数值放在水平方向。三条五分类系列、单位后缀和数据标签分别配置;浮动图例仍须保留可读位置。</p><iframe title="条形、分类和标签的实际运行图表" src="../columns.html#case-bar" style="width:100%;height:650px;border:0"></iframe><p><a href="../columns.html#case-bar" target="_blank" rel="noopener">新窗口打开完整实验</a></p></main></body></html>
尝试一下 ↗ 在独立页面修改并运行
- bar把分类放在垂直方向、数值放在水平方向。三条五分类系列、单位后缀和数据标签分别配置;浮动图例仍须保留可读位置。
- 图表外框、绘图区和图例是不同区域。数据标签可因碰撞隐藏,不能只按标签节点数证明所有文字都可见;值、长度及坐标应一起核对。
条形堆叠的三种状态
展开查看收起
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="robots" content="noindex,nofollow"><title>条形堆叠的三种状态 | 蓝色天空网 mbsky.com</title><link rel="stylesheet" href="../bootstrap.css"><script defer src="../lesson-view.js"></script></head><body data-section="case-bar-stacked" data-mode=""><header>蓝色天空网 · mbsky.com</header><main><h1>条形堆叠的三种状态</h1><p>series.stacking:normal可用于条形累计;percent显示占比;null取消累计。系列间同分类对应关系不能靠数组长度推断。</p><iframe title="条形堆叠的三种状态的实际运行图表" src="../columns.html#case-bar-stacked" style="width:100%;height:650px;border:0"></iframe><p><a href="../columns.html#case-bar-stacked" target="_blank" rel="noopener">新窗口打开完整实验</a></p></main></body></html>
尝试一下 ↗ 在独立页面修改并运行
- series.stacking:normal可用于条形累计;percent显示占比;null取消累计。系列间同分类对应关系不能靠数组长度推断。
- 分别点击三个按钮核对总量、百分比之和与取消状态。图例隐藏系列会影响可见组成,报表应解释分母和单位而不是只换图形。
负值条形
展开查看收起
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="robots" content="noindex,nofollow"><title>负值条形 | 蓝色天空网 mbsky.com</title><link rel="stylesheet" href="../bootstrap.css"><script defer src="../lesson-view.js"></script></head><body data-section="case-bar-negative" data-mode=""><header>蓝色天空网 · mbsky.com</header><main><h1>负值条形</h1><p>负y在水平数值轴相对零向另一侧延伸;这不是设置reversed,也不是将分类逆序。保留三条系列中的负数及其分类。</p><iframe title="负值条形的实际运行图表" src="../columns.html#case-bar-negative" style="width:100%;height:650px;border:0"></iframe><p><a href="../columns.html#case-bar-negative" target="_blank" rel="noopener">新窗口打开完整实验</a></p></main></body></html>
尝试一下 ↗ 在独立页面修改并运行
- 负y在水平数值轴相对零向另一侧延伸;这不是设置reversed,也不是将分类逆序。保留三条系列中的负数及其分类。
- 比较负点与零基线的实际坐标。负数不适合强制yAxis.min:0,否则会裁掉内容;同样不能把负贡献当作正数堆叠。
本章附件与实例包
常见错误与边界检查
- 把配置名、SVG节点或成功加载当成全部教学行为。
- 把本站合成数据、重写实例及自制图称为原始采集成功。
技术规范与官方资料
练习与参考解答
查看参考解答
分别核对数据、轴/系列映射、可见几何、交互和资源清理,不只看退出码。