javascript - 在没有 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")
但这只会改变我的刻度标签的颜色,而不是线条的颜色......我哪里可能出错了?
谢谢
解决方案
当你这样做...
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>
推荐阅读
- mysql - 创建免费的远程数据库并连接到 shinyapp(本地或托管在 AWS/shinyapps.io)
- python - 无法将字符串转换为浮点数:使用 SimpleImputer 的“Mazda RX4”
- alloy - 如果指定了不同签名的范围,为什么 Alloy API 不使用一个签名的默认范围?
- sql - Oracle SQL:COUNT DISTINCT BY 新创建的变量
- python-3.x - Discord 音乐机器人 - 队列 (discord.py)
- angular - 如何在 Angular 中持久化 File 对象?
- android - 警告:NavController.setNavigatorProvider 只能从同一个库组中调用 (groupId=androidx.navigation)
- r - 在R中将数据框改回原始形式
- excel - Excel宏如何禁用行?
- java - java - 如何修复“发生不可恢复的堆栈溢出......Java返回:-1073741819”错误?