Lau*_*nAH 2 javascript css svg d3.js
我正在用 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)
Run Code Online (Sandbox Code Playgroud)
我如何附加它们:
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)
Run Code Online (Sandbox Code Playgroud)
我试图把:
.style("stroke", "#c3c3c3")
Run Code Online (Sandbox Code Playgroud)
在我的 y 轴上是这样的:
var gY = svg.append("g")
.attr("class", "axis--y")
.call(yAxis).style("stroke", "#c3c3c3")
Run Code Online (Sandbox Code Playgroud)
但这只会改变我的刻度标签的颜色,而不是线条......我可能哪里出错了?
谢谢
当你这样做...
svg.append("g").call(yAxis).style("stroke", "#c3c3c3")
Run Code Online (Sandbox Code Playgroud)
...您正在有效地设置包含路径、线条和文本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));
Run Code Online (Sandbox Code Playgroud)
因此,轴生成器设置的那些样式将覆盖您为组设置的样式(在上面的代码中, currentColor 只是CSS currentColor)。
让我们在这个演示中看到它,使用红色表示stroke:
svg.append("g").call(yAxis).style("stroke", "#c3c3c3")
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
如您所见,我们将样式应用于组,但只有文本元素继承了它(它们看起来很难看,因为那是stroke,而不是fill样式)。
解决方案:
选择您想要的元素并将样式应用到它们。
例如,选择线条和路径:
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")Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>Run Code Online (Sandbox Code Playgroud)
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).selectAll("line,path").style("stroke", "red")Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>Run Code Online (Sandbox Code Playgroud)