Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style using d3's .style() method instead of using CSS in style tags for .axis path {}?

I have this d3 code here of an area chart. My question is primarily about styling the axis and the tick marks.

Currently the x axis and y axis are styled like this:

  .axis line {
        fill: none;
        stroke: red;
        shape-rendering: crispEdges;
    }

  .axis path {
        fill: none;
        stroke: blue;
        shape-rendering: crispEdges;
    }

I don't want to use this approach. Let's say I want to change the stroke color of axis (to green), using d3's style() method in my javascript. I tried doing it like this:

svg.append("g")
    .attr("class", "x axis")
    .style("stroke", "green")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

What I ended up changing is the axis text labels to green color. This is not what I intended to do.

What am I missing ?

How do I style .axis line and .axis path using style() method of my d3.

Please find me code here on JSFiddle

like image 465
user3422637 Avatar asked Feb 09 '23 03:02

user3422637


1 Answers

If you want to use javascript

After drawing the axis using selectAll method you can change the colors.

svg.append("g")
    .attr("class", "x axis")
    .style("stroke", "green")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

 svg.selectAll(".x.axis *").style({"stroke":"red"});

I just given an example changed all color to red. you can change only ticks or text color that you want to change.

For line and path use

svg.selectAll(".x.axis line, .x.axis path").style({"stroke":"red"});

But I will prefer to use CSS only for changing color.

like image 56
murli2308 Avatar answered Feb 16 '23 02:02

murli2308