D3 条形图 Y 轴尽管在 DOM 中但未出现

D3 bar graph Y-axis not appearing despite being in DOM

提问人:YMRTZ 提问时间:11/15/2023 更新时间:11/15/2023 访问量:52

问:

使用 d3 制作条形图时,我尝试添加一个 y 轴来显示从 0 到 1 的 2 位小数浮点数。我使用的方法以前有效,只是导致文本元素显示在 DOM 中,但实际上并没有出现在图形上。我将如何修复此错误?

Y 轴相关代码如下所示。

var yscale = d3.scaleLinear().domain([0, 1]).range([height, 0]);
var yaxis = d3.axisLeft(yscale);
svg.append("g")
   .attr("id", "graphYAxis")
   .attr("transform", "translate ( " + 0 + "," + 0 + ")")
   .call(yaxis);

Nothing appears

d3.js

评论


答:

1赞 Akash Ram 11/15/2023 #1

根据问题提供的图像,很明显您已将 svg 元素转换为 (30,40) 而不是 g 元素。因此,您的文本是可见的,但位于 svg 元素之外。要解决此问题,建议遵循 D3.js 库建议的标准边距约定。

const containerWidth = 500   // total width including margins
const containerHeight = 400; // total height including margins
const margin = { top: 30, right: 30, bottom: 30, left: 30 };
const chartWidth = containerWidth - margin.left - margin.right;  // chart width after margin-left and margin-right
const chartHeight = containerHeight - margin.top - margin.bottom; // chart height after margin-top and margin-bottom

// create and configure svg element
const svg = d3
  .create("svg")
  .attr("width", containerWidth)
  .attr("height", containerHeight)

// create a group within the svg element to apply margins
const chartGroup = svg
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);
  
 chartGroup.append("g")
 .attr("id", "graphYAxis")
 .call(yaxis);

请根据您的要求更新代码的其余部分。

评论

0赞 YMRTZ 11/17/2023
这似乎已经解决了它。对齐方式已关闭,但这应该很容易解决 - 文本现在可以正确显示。谢谢!