Sasha
Sasha

Reputation: 8705

D3.js - show tick values on the Y axis

I am trying to write ticks on the y axis in % (0 to 100), but when I use this code only one tick is shown, without the numbers (% label is shown).

Code for the y axis

    var y0 = d3.scale.linear().range([height, 0]);
    var yAxisLeft = d3.svg.axis()
          .scale(y0)
          .orient("left")
          .tickValues(d3.range(0, 100, 10));
    svg.append("g")
          .attr("class", "y axis")
          .style("fill", "steelblue")
          .call(yAxisLeft)
          .append('text')
          .text('%');

This is for the x axis (working as expected):

var x = d3.scale.ordinal()
      .domain(d3.range(m))
      .rangeRoundBands([0, width], .08);
var xAxis = d3.svg.axis()
      .scale(x)
      .tickSize(0)
      .tickPadding(6)
      .orient("bottom");
svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

Upvotes: 3

Views: 3754

Answers (1)

Amani Ben Azzouz
Amani Ben Azzouz

Reputation: 2565

Try ticks(10, "%") instead of tickValues(d3.range(0, 100, 10))

 var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 900- margin.left - margin.right,
    height =450- margin.top - margin.bottom;
    
var svg = d3.select("body").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 + ")");

   var y0 = d3.scale.linear().range([height, 0]);
    var yAxisLeft = d3.svg.axis()
          .scale(y0)
          .orient("left")
          .ticks(10, "%");
          //.tickValues(d3.range(0, 100, 10));
    svg.append("g")
          .attr("class", "y axis")
          .style("fill", "steelblue")
          .call(yAxisLeft)
          .append('text');
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.0/d3.min.js"></script>
<body></body>

Upvotes: 4

Related Questions