gpt4 book ai didi

d3.js - 寻找更好的方法来改变 d3.js v4 中轴组件的颜色

转载 作者:行者123 更新时间:2023-12-02 00:47:37 27 4
gpt4 key购买 nike

我想更改简单 d3.js (v4) 图表的轴颜色。下图中的y轴是成品的示例;

enter image description here

我怀疑我用来实现这一目标的方法有点难看,我相信根据下面的描述应该有一个我还不明白的替代方案。

axis component是文本、路径和线条元素的组合,需要更改各自的样式(描边和填充)。

此时,我发现更改组件颜色的唯一方法是在 <style> 中单独设置样式。代码部分...

.axisRed line{
stroke: red;
}

.axisRed path{
stroke: red;
}

.axisRed text{
fill: red;
}

...稍后在 JavaScript 中附加该类时将该类应用到 y 轴;

  svg.append("g")
.attr("class", "axisRed")
.call(d3.axisLeft(y));

有没有办法可以通过 .style("<some style>", "<some value>") 应用这些样式行,同时附加 y 轴,而不是在 <style> 中声明部分?

代码示例为here .

我尝试过处理单个 DOM 组件,例如“domain”类,但没有成功。我怀疑我对轴组件的层次结构了解不够。

最佳答案

在 D3 上,您有多种选项来设置元素的样式:

选项 A:在您的类中使用样式标签:

axisRed line{
stroke: red;
}

.axisRed path{
stroke: red;
}

.axisRed text{
fill: red;
}
// apply applying that class to the y
svg.append("g")
.attr("class", "axisRed")
.call(d3.axisLeft(y));

选项 B:使用带有自动生成类的样式标签:

D3 为轴线分配domain 类,并在组“g”内为每个刻度类tick 线和text 分配。没有定义特定的类:

<style>
path.domain {
stroke: red;
}
.tick text {
fill:blue
}
</style
.
.
svg.append("g").call(d3.axisLeft(y));

// generate code
<path class="domain" stroke="#000" d="M-6,450.5H0.5V0.5H-6"></path>
<g class="tick" opacity="1" transform="translate(0,414)">
<line stroke="#000" x2="-6" y1="0.5" y2="0.5"></line>
<text fill="#000" x="-9" y="0.5" dy=".32em">50</text>
</g>

选项 C:在附加时间内联

D3 V3上,您可以做得更紧凑:

svg.append("line")
.style({
fill:"none",
stroke:"#f00",
"stroke-width":"10"
})

但是在D3 V4上,不起作用。所以我打开一个“问题”:您可以在此处检查并跟踪进度:https://github.com/d3/d3-selection/issues/82

** 更新 **在 V4 上,您必须包含选择多:

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>

然后使用:styles代替styleattrs而不是attr:

svg.append("line")
.styles({
fill:"none",
stroke:"#f00",
"stroke-width":"10"
})

举个例子:

svg.selectAll(".domain")
.styles({ fill:"none", stroke:"#f00", "stroke-width":"1" });

现在您可以通过一种紧凑的方式来设置元素的样式

额外:您可以设置任何元素的样式和属性:

 var svg = d3.select("body").append("svg")
.attrs({width:600, height:600})
.styles({
border:"1px",
"border-style":"solid",
"border-color":"#f00"})

Here's the plunker

关于d3.js - 寻找更好的方法来改变 d3.js v4 中轴组件的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com