如何在Angular的D3图表中为每个带箭头柱状图创建独立g元素
为每个柱状图与箭头创建独立的g元素解决方案
没问题,我帮你调整代码,让每个柱状图和对应的箭头都拥有独立的<g>容器,这样结构更清晰,也方便后续单独控制样式、绑定事件或添加动画效果。
核心修改步骤:
- 先为每个数据项创建独立的
<g>元素作为容器 - 在每个
<g>内部分别添加箭头线条和柱状图元素
修改后的代码示例:
// 第一步:为每个数据条目创建独立的g容器 const barGroups = bar.enter() .append('g') .attr('class', 'bar-group'); // 给g元素添加类名,方便后续样式或选择操作 // 第二步:在每个独立g中添加箭头线条 barGroups.append("line") .attr("x1", d => this.x(d.phase) + this.x.bandwidth() / 2) .attr("y1", d => this.y(d.start) + ((d.start < d.finish)? -5 : 5)) .attr("x2", d => this.x(d.phase) + this.x.bandwidth() / 2) .attr("y2", d => this.y(d.finish) + ((d.start < d.finish)? 5 : -5)) .attr("stroke", "black") .attr("stroke-width", 3) .attr("marker-end", "url(#arrow)") .style('pointer-events', 'none'); // (可选)如果需要在同一个g中添加柱状图的rect元素,可以补充这段代码 barGroups.append("rect") .attr("x", d => this.x(d.phase)) .attr("y", d => this.y(Math.min(d.start, d.finish))) .attr("width", this.x.bandwidth()) .attr("height", d => Math.abs(this.y(d.start) - this.y(d.finish))) .attr("fill", "steelblue"); // 可根据需求自定义填充颜色
说明:
- 现在每个柱状图(包括箭头)都会被包裹在独立的
<g class="bar-group">元素中,DOM结构更规整 - 后续如果需要针对单个柱状图做交互(比如hover效果),直接操作对应的
bar-group即可,无需担心影响其他元素
内容的提问来源于stack exchange,提问作者ttmt
相关产品推荐
相关产品推荐

