Home > Blockchain >  Changing the color of an axis line in a D3 chart
Changing the color of an axis line in a D3 chart

Time:01-13

I am trying to change the axis to be in red, and I have tried several ways to do it following this link Chart


I changed the code to following

        const textColor = "rgb(230, 230, 230)"
        const opacValue = 1.0


        const xScale = d3.scaleTime().domain(d3.extent(data, function(d) {
            return d3.timeParse("%Y-%m-%d")(d.date);
        })).range([0, width]);
        const yScale = d3.scaleLinear().domain([Math.min(20, d3.min(data, function(d) {
            return  d.TFX;
        })), Math.max(80, d3.max(data, function(d) {
            return  d.TFX;
        }))]).range([height, 0]);


        const xAxis = d3.axisBottom(xScale).tickFormat(d3.timeFormat("%b"))
        const yAxis = d3.axisLeft(yScale)

        const gXAxis = svg.append("g").attr("transform", "translate(0,"   height   ")")
        const gYAxis = svg.append("g")

        gXAxis.call(xAxis)
        gYAxis.call(yAxis)

        gYAxis.selectAll('.tick line').attr('opacity', opacValue).attr('stroke', textColor)
        gYAxis.selectAll('.domain').attr('opacity', opacValue).attr('stroke', textColor)
        gYAxis.selectAll('.tick').attr('opacity', opacValue).attr('stroke', textColor)
        gYAxis.append("text").attr("text-anchor", "end").attr("x", -25).attr("y", height * 0.5).attr("stroke", textColor).text("%")

        gXAxis.selectAll('.tick line').attr('opacity', opacValue).attr('stroke', textColor)
        gXAxis.selectAll('.domain').attr('opacity', opacValue).attr('stroke', textColor)
        gXAxis.selectAll('.tick').attr('opacity', opacValue).attr('stroke', textColor)
        gXAxis.selectAll('text').attr("y", 0).attr("x", 9).attr("dy", ".35em").style("text-anchor", "start").attr("transform", "rotate(45)")
        gXAxis.append("text").attr("text-anchor", "end").attr("x", innerWidth * 0.5).attr("transform", "translate(0,"   30   ")").attr("stroke", textColor).text("Time")

CodePudding user response:

First, separate the code of axis from its parts:

const axisBottom = d3.axisBottom(x)
  .tickFormat(d3.timeFormat("%b"));

const axisBottomG = svg.append("g")
  .attr("transform", "translate(0,"   height   ")")
  .call(axisBottom);

axisBottomG.classed('axisGrey', true);

axisBottomG.selectAll("text")
  .attr("y", 0)
  .attr("x", 9)
  .attr("dy", ".35em")
  .attr("transform", "rotate(45)")
  .style("text-anchor", "start");

Then, inspect (F12) axis <g> element to make sure it has axisGrey class and has the class styles as well.

  •  Tags:  
  • Related