kaybuzz
kaybuzz

Reputation: 117

D3 align text along the right axis

Bar graph

In this picture, the large numbers (100.00001, 200.000001, 300.00001, 400.00001) are correct in that they align with the bar graph axis. The problem occurs for the small numbers when the bars are not large enough to fit this text, so it spills to the right side of the axis. How do I fix this problem to align all numbers on the left of the axis regardless of the bar size.

var data = [200.000001,3.00001,300.00001,1.00001,400.00001,5.0001,100.00001,20.0001,40.0001,50.00001, 2.00001];

//bar chart
var bars = d3.select("#chart").append("div").attr("class","chartstyle");
var b = bars.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return d  + "px"; })
.text(function(d) { return d; });


//from stylesheet
<style>
.chartstyle div {
    font: 10px;
    background-color: red;
    text-align: right;
    padding: 0px;
    margin: 0px;
    color: black;
}
</style>

Upvotes: 0

Views: 1072

Answers (1)

CodeCheshire
CodeCheshire

Reputation: 730

First of all, d3js is usually at its best when working with svg's as opposed to divs so the best solution would probably be to create svg rects and text elements and then set the x and y coordinates on each one.

That being said, it is still possible to achieve what you want through using d3js and css like you have in your example. The solution would be to apply absolute positioning to the text - see below:

var data = [200.000001, 3.00001, 300.00001, 1.00001, 400.00001, 5.0001, 100.00001, 20.0001, 40.0001, 50.00001, 2.00001];

//bar chart
var chart = d3.select("#chart").append("div").attr("class", "chartstyle");
var bars = chart.selectAll("div").data(data);
bars.enter().append("div")
  .attr("class", "rect")
  .style("width", function(d) {
    return d + "px";
  })
  .style("height", "20px");
bars.append("div")
  .attr("class", "numericVal")
  .text(function(d) {
    return d;
  })
  .style("height", "20px");
.chartstyle {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding-right: 100px;
}

.rect {
  background-color: red;
  text-align: right;
  padding: 0px;
  margin: 0px;
  color: black;
  position: relative;
}

.numericVal {
  position: absolute;
  right: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="chart"></div>

Upvotes: 2

Related Questions