首页 > 解决方案 > 如何仅更改 D3.js 图表中数据网格或 x 和 y 轴的颜色

问题描述

我在这里创建了 JSFiddle -

我想从 X 和 Y 轴制作单独的数据网格。非常轻的 DataGrid 和深色的 X 和 Y 轴

我试过了,但它总是取笔画=路径域中的当前颜色

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g") // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis);

这是CSS

.axis line {
    stroke: red !important;
    opacity: 0.3;
}

.axis path {
    stroke: red !important;
    opacity: 0.3;
}

.axis text {
    fill: red !important;
}
    [![enter image description here][2]][2]

标签: angularjsd3.js

解决方案


有两种方法可以解决这个问题:

有一个 d3 解决方案,基本上不需要 css

svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .call(g => g.selectAll(".tick:first-of-type line")
                .attr("class", "axis_bar")
                .attr("stroke", "black"))
    .call(g => g.selectAll(".tick:not(:first-of-type) line")
                .attr("class", "axis_y_tick")
                .attr("stroke", "red"));

svg.append("g") // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis)
    .call(g => g.selectAll(".tick:first-of-type line")
                .attr("class", "axis_bar")
                .attr("stroke", "black"))
    .call(g => g.selectAll(".tick:not(:first-of-type) line")
                .attr("class", "axis_y_tick")
                .attr("stroke", "red"));
          
svg.append("path") // Add the valueline path.
    .attr("d", valueline(data))
    .attr("class", "graph")
    .attr("stroke", "blue")
    .attr("stroke-width", 2);

这将选择第一行和后面的每一行并应用不同的样式参数。

第二种解决方案是仅在 css 中执行此操作。您可能会在 d3 代码段中看到您需要的类选择器:

.tick:first-of-type line {} //Selects the first Tick/Line wich becomes the main axis.

.tick:not(:first-of-type) line {} // Will select every other tick line, but the first.

我编辑了你的小提琴适合 d3 解决方案:http: //jsfiddle.net/nk13jycw/2/

Mike Bostock 对此也有很好的观察:https ://observablehq.com/@d3/styled-axes


推荐阅读