Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

javascript - X Axis text labels are not rotating in d3

I am working with a D3 stack bar chart.

The fiddle is here

When I am clicking on the Month button, the chart appears with a messy x axis label enter image description here

I want to rotate the x-axis label's conditionally in case of a good amount of data (In the fiddle, for months data)

My first step is to rotate the label. I am appending the below part.

  svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .selectAll("text")  
            .style("text-anchor", "end")
            .attr("dx", "-.8em")
            .attr("dy", ".15em")
            .attr("transform", "rotate(-65)" );

I am not sure, why it is not working. Whats the problem here?

question from:https://stackoverflow.com/questions/65920124/x-axis-text-labels-are-not-rotating-in-d3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's nothing wrong with your code - see below:

var margin = {top: 25, right: 25, bottom: 25, left: 25}
var width = 600 - margin.left - margin.right;
var height = 200 - margin.top - margin.bottom;

// x domain
var x = d3.timeDays(new Date(2020, 00, 01), new Date(2025, 11, 01));

// x scale
var xScale = d3.scaleTime()
  .domain(d3.extent(x))
  .range([0, width]); 

// svg
var svg = d3.select("#scale")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);
   
// messy x-axis
svg.append("g")
  .attr("class", "x-axis")
  .attr("transform", `translate(0,${height - 50})`)
  .call(d3.axisBottom(xScale)
    .ticks(d3.timeMonth)
  );

// x-axis with rotated labels
svg.append("g")
  .attr("class", "x-axis")
  .attr("transform", `translate(0,0)`)
  .call(d3.axisBottom(xScale)
    .ticks(d3.timeMonth)
  )
  .selectAll("text") // YOUR CODE
  .style("text-anchor", "end") // YOUR CODE
  .attr("dx", "-.8em") // YOUR CODE
  .attr("dy", ".15em") // YOUR CODE
  .attr("transform", "rotate(-65)" ); // YOUR CODE 
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.3.1/d3.min.js"></script>
<div id="scale"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...