如何为NVD3 MultiBarChart的图例添加自定义标题?
给NVD3 MultiBarChart图例添加自定义标题
要给NVD3的MultiBarChart图例加上类似“Status”的标题,咱们可以利用D3直接操作图表渲染后的DOM元素——因为NVD3会自动生成图例容器,我们只需要在这个容器里插入标题文本即可。
解决方案步骤
- 等待图表完成渲染(在
nv.addGraph的回调函数里操作最稳妥) - 选中NVD3生成的图例容器(类名为
.nv-legend) - 在图例元素的最前面插入自定义标题文本,并设置合适的样式让它和图例项对齐
修改后的完整代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.css" rel="stylesheet" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js" charset="utf-8" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.js"></script> <style> text { font: 12px sans-serif; } svg { display: block; } html, body, #chart1, svg { margin: 0px; padding: 0px; height: 100%; width: 100%; } /* 可选:给图例标题加一点右边距,和图例项分开 */ .nv-legend-title { margin-right: 8px; } </style> </head> <body> <div id="chart1"> <svg></svg> </div> <script> var selector = "#chart1 svg"; var XaxisLabel = "Project"; var YaxisLabel = "Count"; var Data = [ { key: "Complete", values: [ { label: "Pr1", value: 2 }, { label: "Pr2", value: 2 }, { label: "Pr3", value: 2 } ], color: "blue" }, { key: "In progress", values: [ { label: "Pr1", value: 2 }, { label: "Pr2", value: 1 }, { label: "Pr3", value: 1 } ], color: "red" } ]; nv.addGraph(function () { var chart = nv.models .multiBarChart() .x(function (d) { return d.label; }) .y(function (d) { return d.value; }) .duration(1300) .margin({ bottom: 100, left: 70 }) .rotateLabels(0) .groupSpacing(0.1); chart.reduceXTicks(false).staggerLabels(false); chart.xAxis .axisLabel(XaxisLabel) .axisLabelDistance(35); chart.yAxis .axisLabel(YaxisLabel) .axisLabelDistance(-5) .showMaxMin(false); d3.select(selector).datum(Data).call(chart); // 关键:添加图例标题 d3.select(selector + " .nv-legend") .insert("text", ":first-child") .text("Status") .attr("class", "nv-legend-title") .style("font-weight", "bold") .style("alignment-baseline", "middle") .attr("dy", "0.35em"); nv.utils.windowResize(chart.update); return chart; }); </script> </body> </html>
代码说明
insert("text", ":first-child"):确保标题插入在所有图例项的最前面alignment-baseline: middle和dy: 0.35em:让标题文本和图例的圆形标记垂直对齐- 我们还加了一个自定义类
.nv-legend-title,方便你后续调整样式(比如加右边距)
这样修改后,图表右上角的图例就会显示成 Status ○ Complete ○ In progress 的效果啦。
内容的提问来源于stack exchange,提问作者Stéphane Laurent
相关产品推荐
相关产品推荐

