How to display value labels above graph bars? - javascript

Is there a way to display values above the bars in this graph? I have the values being retrieved from a TSV, but am currently having difficulty getting the bar values to be displayed as labels above each respective bar.
This is the data that I have as TSV:
This is what I currently have for rendering the graph:
margin =
top: 30
right: 30
bottom: 40
left: 60
width = 960 - margin.left - margin.right
height = 500 - margin.top - margin.bottom
formatPercent = d3.format("")
x = d3.scale.ordinal()
.rangeRoundBands([width, 0], .1)
y = d3.scale.linear()
.range([height, 0])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatPercent)
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent)
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 + ")")
d3.tsv("/Home/GetTsv/data.tsv", (error, data)->
data.forEach((d)->
d.Total = +d.Total
)
x.domain(data.map((d)-> d.Year))
y.domain([0, d3.max(data, (d)-> d.Total)])
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("y", 30)
.attr("x", width / 2)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Year")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -60)
.attr("x", -(height / 2))
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Total Activity")
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d)-> x(d.Year))
.attr("width", x.rangeBand())
.attr("y", (d)-> y(d.Total))
.attr("height", (d)-> height - y(d.Total))
# svg.selectAll("text")
# .data(data)
# .enter()
# .append("text")
# .text((d)-> d.Total)
# .attr("x", (d, i)-> i * (width / data.length))
# .attr("y", (d)-> height - d)
)
This is what my graph looks like:
But I would like to have labels above the bars, similar to this:
The code that is commented-out is my attempt at trying to make the value labels show above the bars.

Pasting this code in the text section should do the trick:
.attr("text-anchor", "middle")
.attr("x", function(d, i) { return i * (width / dataset.length) + (width / dataset.length) / 2; })
.attr("y", function(d) { return height - (d * 10) - 10; })
the -10 there makes some distance from the bar, in this case 10px obviously. also the other numbers are to be tweaked a bit, i just pasted the code from a file i had so i don't know exactly what it would look like on your code since i don't have the dataset to try.
If it doesn't can you paste the script in http://jsfiddle.net/ so I can try and work it out? Let me know how it works out!

Related

Creating a bar chart using d3

So I'm trying to create a bar chart using d3 and here's my code, for some reason, the bar chart won't show up and I'm getting an error saying:
remote-work.js:14 Uncaught (in promise) TypeError: Cannot read property 'linear' of undefined
at drawBars (remote-work.js:14)
Can anyone advise me on where I'm going wrong it would be greatly appreciated.
async function drawBars() {
// 1. Access data
const data = await d3.csv("./../remote_work.csv")
console.log(data);
//chart = {
const margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom
const x = d => d.Benefits
const y = d3.scale.linear()
.range(height, 0);
const xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
const yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
const 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 + ")");
x.domain(data.map(function(d) { return d.Benefits; }));
y.domain([0, d3.max(data, function(d) { return d.Percentage; })]);
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", "-.55em")
.attr("transform", "rotate(-90)" );
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("Percentage ($)");
svg.selectAll("bar")
.data(data)
.enter().append("rect")
.style("fill", "steelblue")
.attr("x", function(d) { return x(d.Benefits); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.Percentage); })
.attr("height", function(d) { return height - y(d.Percentage); });
}
drawBars()

Correctly format year on x axis d3

I am working with a scatterplot in d3. The x axis represents the YEAR. I get information from the database and plot it as circles on the graph. My problem is how do I parse the x value so it is formatted as a year? ie. currently it displays like 1,999 but it should look like 1999. Can someone show me how I should parse this correctly to get the right format! Here is the relevant code:
var margin = {top: 20, right: 20, bottom: 30, left: 60},
width = 1800 - margin.left - margin.right,
height = 600- margin.top - margin.bottom;
var YearFn = function(d) {return d.YEAR ;};
var Num_citationsFn = function(d) {return d.counter;};
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
d3.json("connection4.php", function(error,data) {
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = d.counter;
x.domain([d3.min(data, YearFn)-1, d3.max(data, YearFn)+1]);
y.domain([d3.min(data, Num_citationsFn)-1, d3.max(data, Num_citationsFn)+1]);
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 + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", -6)
.style("text-anchor", "end")
.text("YEAR");
// y-axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of citations");
var circles = svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 8.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill","blue")
});
I appreciate any feedback I am new to d3! Thanks in advance!
xAxis.tickFormat(d3.format('0f'));

Multiple Bar charts with fixed y-axis to highlight the different as shown in fig

I looking any chart library which has configuration for custom y-axis values. I want to customize the y-axis like ( 0 to 3). I seen D3 and other chart libraries, the Y-axis automatically generates the values. I my design there is only one filed and on one for compare on the x-axis.
Which chart library is most suited for this condition to make this happen. If any example already on google, please share...
If you are looking for a D3 solution then you can refer my fiddle below:
http://jsfiddle.net/cyril123/7ftuumv4/2/
code:
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
//specify data here
data = [{letter: "1", value: 1.3}]
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
;
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 + ")");
//as you have a fixed x axis value and single data
x.domain([data[0].letter]);
//as you have a fixed range for y axis
y.domain([0, 3]);
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");
//make the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });

D3 barchart: first bar overlaps axis label

I have built a barchart with D3 but I'm running into these 2 minor issues which I am not be able to fix.
1) The first bar of the barchart overlaps the y axis
2) The labels of the y axis ticks are disappearing on the left side when the number(Volume) exceeds 1 million.
Here is a snapshot of what is happening:
Here's my D3 code:
function drawGraph(dataGraph){
if (dataGraph.length == 0){
$('#graph-container').append('<h3>No Data Match</h3>');
return;
}
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 900 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom,
padding = 15;
var max = d3.max(dataGraph, function(d) { return +d.VOLUME;} );
var maxDate = d3.max(dataGraph, function(d) { return +d.AS_OF_DATE;} );
var x = d3.scale.ordinal()
.domain(dataGraph.map(function(d) {return d.AS_OF_DATE;}))
.rangeRoundBands([0, (width- padding )], .1);
var y = d3.scale.linear()
.domain([0,max])
.range([height,0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
var yAxis = d3.svg.axis()
.scale(y)
.orient('left')
.ticks(10);
var svg = d3.select("#graph-container")
.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 + ")");
svg.append('g')
.attr('class', 'x axis')
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.style("color", "#333")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" );
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("color", "#333")
.text("Volume");
svg.selectAll('.bar')
.data(dataGraph)
.enter().append('rect')
.attr('class', 'bar')
.attr("x", function(d) { return x(d.AS_OF_DATE); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.VOLUME); })
.attr("height", function(d) { return height - y(d.VOLUME); });
}

Colour of points repeat after 10 data sets on D3.js scatter plot

Problem:
I've got a D3.js scatter plot that has 16 different data sets, but it seems like D3 has only 10 different colours built-in before it repeats. You can see what I mean by clicking that link.
Code:
function updatePlot() {
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
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 + ")");
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.sepalLength = +d.sepalLength;
d.sepalWidth = +d.sepalWidth;
});
x.domain(d3.extent(data, function(d) { return d.sepalWidth; })).nice();
y.domain(d3.extent(data, function(d) { return d.sepalLength; })).nice();
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", -6)
.style("text-anchor", "end")
.text("HPF/LPF Intensity Ratio");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("HPF Intensity (relative units)")
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) { return x(d.sepalWidth); })
.attr("cy", function(d) { return y(d.sepalLength); })
.style("fill", function(d) { return color(d.species); });
var legend = svg.selectAll(".legend")
.data(color.domain())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
}
(The code is pretty much copy/paste from here with a little customisation in the areas of D3 that I understand)
Thanks!
This part of the docs has the answer: Ordinal-Scales#categorical-colors. Thanks to user and Lars Kotthoff!
Simply replaced category10 with category20.

Categories