首页 > 解决方案 > 在没有 CSS 的情况下设置轴的样式

问题描述

我正在用 d3 构建一个折线图,并试图让我的刻度为灰色,而我的轴和刻度标签将是深灰色。如何在不使用 CSS 的情况下在 d3 中设置此内联样式?我似乎不太对劲。提前致谢!

这就是我构建 x 和 y 轴的方式:

var xAxis = d3.axisBottom(x)
  .scale(x)
  .ticks((width + 2) / (height + 2))
  .tickSize(-height)
  .tickPadding(10)
  .tickFormat(d3.timeFormat("%b %d, %H:%M:%S"))


var yAxis = d3.axisLeft(y)
  .scale(y)
  .ticks(5)
  .tickSize(-(width - 100))
  .tickPadding(10)

我如何附加它们:

var gX = svg.append("g")
  .attr("class", "axis--x")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
var gY = svg.append("g")
  .attr("class", "axis--y")
  .call(yAxis)

我试图说:

.style("stroke", "#c3c3c3")

在我的 y 轴上是这样的:

var gY = svg.append("g")
  .attr("class", "axis--y")
  .call(yAxis).style("stroke", "#c3c3c3")

但这只会改变我的刻度标签的颜色,而不是线条的颜色......我哪里可能出错了?

谢谢

标签: javascriptcssd3.jssvg

解决方案


当你这样做...

svg.append("g").call(yAxis).style("stroke", "#c3c3c3")

...您正在有效地设置包含路径、行和文本stroke的元素。<g>显然,您希望这会设置所有这些元素的样式。

但是,D3 轴生成器会自动设置<line><path>元素的样式。让我们看一下源代码

path = path.merge(path.enter().insert("path", ".tick")
    .attr("class", "domain")
    .attr("stroke", "currentColor"));

line = line.merge(tickEnter.append("line")
    .attr("stroke", "currentColor")
    .attr(x + "2", k * tickSizeInner));

因此,由轴生成器设置的那些样式将覆盖您为组设置的样式(在上面的代码中, currentColor 只是CSS currentColor)。

让我们在这个演示中看到它,使用红色表示stroke

const svg = d3.select("svg");
const g = svg.append("g");
const axis = d3.axisBottom(d3.scaleLinear().range([10, 290]));
g.call(axis).style("stroke", "red")
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

如您所见,我们将样式应用于组,但只有文本元素继承了它(它们看起来很丑,因为那是stroke,而不是fill样式)。

解决方案

选择您想要的元素并将样式应用到它们。

例如,选择线条和路径:

const svg = d3.select("svg");
const g = svg.append("g");
const axis = d3.axisBottom(d3.scaleLinear().range([10, 290]));
g.call(axis).selectAll("line,path").style("stroke", "red")
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>


PS:由于新版本的 D3 使用currentColor,您可以使用color属性绘制所有内容!看一看:

const svg = d3.select("svg");
const g = svg.append("g");
const axis = d3.axisBottom(d3.scaleLinear().range([10, 290]));
g.call(axis).style("color", "red")
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>


推荐阅读