Y axis ticks with wrong rotation - javascript

I have a d3 graph in which the x axis ticks are like this:
The code segment for doing that is the following
vis.append("svg:g")
.attr("class", "x axis")
.style({ 'stroke': 'Black', 'fill': 'none', 'stroke-width': '1px' })
.attr("transform", "translate(0," + (height - margin.bottom) + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 9)
.attr("dy", "0.35em")
.attr("transform", "rotate(120)")
.style("text-anchor", "start");
The thing is that labels are not readable. For example, "August" should start with "A", not with "t" like in the image I've attached.
I tried changing "rotate" value, even it did not help.
Can someone help me to position the labels correctly ?

Instead of rotating 120, try to rotate -40 (changing the text-anchor to end).
Here is the demo:
var svg = d3.select("svg")
var scale = d3.scaleBand()
.range([20, 280])
.domain(["foo", "bar", "baz"]);
var axis = d3.axisBottom(scale);
var gX = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis)
.selectAll("text")
.attr("transform", "translate(-10,0) rotate(-40)")
.style("text-anchor", "end");
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Related

How to transform (rotate) svg text element without changing coordinates?

I'm new to this d3.js. Here I'm trying to draw a bar chart using the d3.v3.js library. Here I'm facing few problems. I have tried to include measure labels onto the y-axis. But once I transform the labels -90 degree its position is automatically changing.
Here's the code I'm used to drawing:
svg.append("g")
.attr("id","x_axis")
.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)");
// .attr("transform", "translate(" + bandSize + ", 0)")
svg.append("g")
.attr("class", "x axis")
.attr("id","dimLabel")
.append("text")
.style("text-anchor", "end")
.attr("x", width/2)
.attr("y", height+55)
.text(dimensionLabels[0]);
svg.append("g")
.attr("id","y_axis1")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("class", "label")
//.attr("transform", "rotate(-90)")
.attr("y", function(d){return y(d3.max(data, function(d) { return d.Metric1; }));});
//Measure Labels
svg.append("g")
.attr("class", "y axis")
.attr("id","measureLabels")
.append("text")
.style("text-anchor", "end")
.attr("x", 0)
.attr("y", height/2)
.text(measureLabels[0]+", "+measureLabels[1])
.attr("transform", "rotate(-90)");
Output Image:
Any help is greatly appreciated.
What you see right now is the expected result, because the rotate function of the transform attribute rotates the element around the origin (0,0), not around its center.
The easiest solution is dropping your attr("x") and attr("y") and positioning the text using the same transform:
var width = 300,
height = 300;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var text = svg.append("text")
.text("Sum (sales), Sum (quantity)")
.attr("text-anchor", "middle")
.attr("transform", "translate(20," + (height / 2) + ") rotate(-90)")
svg {
border: 1px solid gray;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
Another solution is setting the center of the rotate to the same x and y values:
var width = 300,
height = 300;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var text = svg.append("text")
.text("Sum (sales), Sum (quantity)")
.attr("text-anchor", "middle")
.attr("x", 20)
.attr("y", 150)
.attr("transform", "rotate(-90, 20, 150)")
svg {
border: 1px solid gray;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
I think you are looking for the css property transform-origin
https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin

In d3, how do I include text and a background box as I roll over my line chart?

I'm using d3 v4. I want to display some text corresponding to where folks are mousing-over my line chart and I would like to have a background box on this text. So I'm trying this
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Value");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");
focus.append("circle")
.attr("r", 4.5);
var rect = focus.append("rect")
.attr("x", 9)
.attr("dy", ".35em")
.attr("width", 50)
.attr("height", 50)
.attr("fill", "yellow");
...
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.attr("transform", "translate(" + x(d.index_date) + "," + y(d.value) + ")");
rect.select("text").text(formatCurrency(d.value));
}
but what is happening instead is there is just a rectangle without any text floating over my mouseover point as you can see here -- https://jsfiddle.net/xx77tzn3/9/. How do I adjust what I have to include the text and a background box?
<svg>'s (rather unintuitively) don't allow you to append text elements to rect elements. Uncomment
//var text = focus.append("text")
and comment out:
var text = rect.append("text")
Then it the mouse function, change line 113 to this:
focus.select("text").text(formatCurrency(d.value));
Then it's just a matter of formatting the text on that <g>.
EDIT: in order to format the text to be on the rect, you need to make the coordinates of the text relative to the <g>, not the rect. I.e.:
var text = focus.append("text")
//var text = rect.append("text")
.attr("x", 10)
.attr("y", 10);
Now the text is there, and on top of the rectangle.
Updated js.fiddle

D3 - X Axis labels are overlapping

I'm create a line chart using D3 v4 and the labels X are overlapping.
// Add the X Axis
var xAxis = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)
.tickValues(data.map(d=>d.date))
.tickFormat(d3.timeFormat("%d/%m %H:%M")))
.selectAll("text")
.attr("transform", "rotate(90)")
.attr("dy", ".35em")
.attr("y", 0)
.attr("x", 9)
.style("text-anchor", "start");
The full code is here: JSFiddle
Do not use given tick values. The data points near the right end of the chart are too close to each other for doing this. Just remove this line
.tickValues(data.map(d=>d.date))
Show the exact times in a tooltip if they are important.

D3js X AXIS time - out of range

I did a graph where my x-axis is out of the range in svg element.
I am using object structure ProgressGraph to save my options (because of another things...)
I would like to set x-axis to fixed size 720x450, but when I call zoom or I want to translate graph to right / left , the X-axis is going out of the svg element. The x-axis size width is changing from 720 to 920.53 and I do not know why. This width should be fixed to 720px.
Screenshots:
Good One good one before zoom / move to side
Bad One bad one after zoom / move to side
graphParams : {
//whole size
width : 1050,
height : 600,
//svg -g
svg_width: 720,
svg_height : 450
}
x = d3.time.scale().domain(ProgressGraph.xAxisDomain).range([0,graphParams.svg_width]);
xAxis =
d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-graphParams.svg_height)
.tickPadding(12)
.ticks(12);
yAxis =
d3.svg.axis()
.scale(y)
.orient("left")
.tickSize(-graphParams.svg_width);
zoom =
d3.behavior.zoom()
.x(x)
.scaleExtent([1, 32])
.on("zoom", zoomed);
var svg = d3.select("#projectProgress-graph-div").append("svg")
.attr("width", graphParams.width)
.attr("height", graphParams.height)
.append("g")
.attr("id", "projectProgress-graph-svg")
.attr("transform", "translate(" + (graphMargin.left) + "," + graphMargin.top + ")")
.call(zoom);
svg.append("rect")
.attr("width", graphParams.svg_width )
.attr("height", graphParams.svg_height);
svg.append("g")
.attr("class", "x axis")
.attr("width", graphParams..svg_width)
.attr("transform", "translate(0, " + graphParams.svg_height + ")")
.call(xAxis)
.selectAll("text")
.attr("dx", "-2em")
.attr("dy", ".0em")
.attr("transform", "rotate(-65)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function zoomed() {
svg.select(".x.axis").call(xAxis)
.selectAll("text")
.attr("dx", "-2em")
.attr("dy", "0em")
.attr("transform", "rotate(-65)" );
}
Sollution is add a svg element befero we add "g element" for x axis
svg.append("svg")
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0 , " + graphParams.svg_height + ")")
.call(xAxis)
.selectAll("text")
.attr("dx", "-2em")
.attr("dy", ".0em")
.attr("transform", "rotate(-65)" );

How do I make a basic column(vertical) chart in d3js?

I'm trying out d3js and I have a problem with getting my first basic column(vertical bar) chart work. The only thing I find a bit difficult to understand is the scaling thing. I want to make the x and y axis ticks with labels but I have the following problems:
First of all here is my data:
{
"regions":
["Federal","Tigray","Afar","Amhara","Oromia","Gambella","Addis Ababa","Dire Dawa","Harar","Benishangul-Gumuz","Somali","SNNPR "],
"institutions":
[0,0,34,421,738,0,218,22,22,109,0,456]
}
On the y-axis the values are there but the order is reversed. Here is the code:
var y = d3.scale.linear().domain([0, d3.max(data.institutions)]).range([0, height]);
then I use this scale to create a y-axis:
var yAxis = d3.svg.axis().scale(y).orient("left");
and add this axis to the svg element
svgContainer.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Institutions");
the problem here is that the y-axis start from 0 at the top and with 700 at the bottom which is OK but it should be in reverse order.
The other problem I have it the x-axis. I want to have an ordinal scale since the values I want to put are in the regions names I have above. So here's what I've done.
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) { return d.substring(0, 2); }))
.rangeRoundBands([0, width], .1);
then the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
and finally add it to the svg element
svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate( 0," + height + ")")
.call(xAxis);
Here the problem is the ticks as well as the labels appear but they are not spaced out evenly and do not correspond with the center of the rectangles I'm drawing. Here is the complete code so you can see what's happening.
$(document).ready(function(){
d3.json("institutions.json", draw);
});
function draw(data){
var margin = {"top": 10, "right": 10, "bottom": 30, "left": 50}, width = 700, height = 300;
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) { return d.substring(0, 2); }))
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.domain([0, d3.max(data.institutions)])
.range([0, height]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svgContainer = d3.select("div.container").append("svg")
.attr("class", "chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" +margin.left+ "," +margin.right+ ")");
svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate( 0," + height + ")")
.call(xAxis);
svgContainer.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Institutions");
svgContainer.selectAll(".bar")
.data(data.institutions)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {return i* 41;})
.attr("y", function(d){return height - y(d);})
.attr("width", x.rangeBand())
.attr("height", function(d){return y(d);});
}
I put the code to Fiddle: http://jsfiddle.net/GmhCr/4/
Feel free to edit it! I already fixed both problems.
To fix the upside-down y-axis just swap the values of the range function arguments:
var y = d3.scale.linear().domain([0, d3.max(data.institutions)]).range([height, 0]);
Do not forget to adjust the code for the bars if you change the scale!
The source of the mismatch between bars and the x-axis can be found here:
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) {
return d.substring(0, 2);}))
.rangeRoundBands([0, width], .1);
svgContainer.selectAll(".bar")
.data(data.institutions)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {return i* 41;})
.attr("y", function(d){return height - y(d);})
.attr("width", x.rangeBand())
.attr("height", function(d){return y(d);});
You specify the padding for rangeRoundBands at 0.1 but you ignore the padding when computing the x and width values for the bars. This for example is correct with a padding of 0:
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) {
return d.substring(0, 2);}))
.rangeRoundBands([0, width], 0);
svgContainer.selectAll(".bar").data(data.institutions).enter().append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {
return i * x.rangeBand();
})
.attr("y", function(d) {
return y(d);
})
.attr("width", function(){
return x.rangeBand();
})
.attr("height", function(d) {
return height -y(d);
});
The padding determines how much of the domain is reserved for padding. When using a width of 700 and a padding of 0.1 exactly 70 pixels are used for padding. This means you have to add 70 / data["regions"].length pixels to every bar's x value to make this work with a padding.

Categories