Good afternoon.
I need to automatic update the size of the chart.
My code is above.
My data is something like this, when the data is small i do not have problem but when it is big the values in xAxis and the bars are overlapping.
var data = [
{key:1, value:5},
{key:2, value:10},
{key:3, value:15},
{key:4, value:26},
{key:5, value:33}
];
var margin = {
top: 30,
right: 10,
bottom: 30,
left: 30
},
width = 900 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.map(function(d) {
return d.key;
}))
.rangeRoundBands([margin.left, width], 0.05);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) {
return d.value;
})])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var key = function(d) {
return d.key;
};
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right + 10)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.text("Your tooltip info")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("Log(number sts) vs Nodes - Gen" + " " + startGen + " "+"to" + " "+ endGen)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(-30," + height + ")")
.call(xAxis)
.append("text")
.attr("x", width)
.attr("dy", 30)
.attr("text-anchor", "end")
.text("Number of nodes");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -30)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Log(Number Sts)");
var bars = svg.selectAll("rect")
.data(data, key)
.enter().append("rect")
.attr("x", function(d) {
return x(d.key) + x.rangeBand() / 2 - 40;
})
.attr("y", function(d) {
return y(d.value);
})
.attr("width", 20)
.attr("height", function(d) {
return height - y(d.value);
})
.style("fill", "blue");
If you want to size the chart according to how much data you have then you can simply replace your "width" variable with a calculation: something like:
width = Math.min(900, 20 * data.length);
But perhaps what you mean is to size the bars based on how much room there is? You are already using x.rangeBand that gives you the available range width - try using that for the bar width
...
.attr("width", x.rangeBand())
If you want to get fancy you can have finer control over the bar width and gap. Something like:
var barWidth = Math.max(1, 0.9 * x.rangeBand());
var halfGap = Math.max(0, x.rangeBand() - barWidth) / 2;
var bars = svg.selectAll("rect")
.data(data, key)
.enter().append("rect")
.attr("x", function(d) {
return x(d.key) + halfGap - 30 ;
})
.attr("width", barWidth)
...
You can try the fiddle here
Related
I am new to d3 and trying to make a grouped bar chart following this and this websites.
The following is my code for the scales
x0 = d3.scaleTime()
.domain([
d3.min(dataset, function(d) {return d.date;}),
d3.max(dataset, function(d) {return d.date;})
])
.range([0,w]);
x1 = d3.scaleOrdinal()
.domain([dataset.WorldPopulation, dataset.InternetUser]);
// .rangeRound([0, x0.bandwidth()]);
y = d3.scaleLinear()
.domain([0, d3.max(dataset, function(d) {return d.WorldPopulation})])
.range([h,0]);
In the website above they use scaleOrdinal but I used scaleTime as x0. Therefore I'm not too sure if that works.
This is my code for the append(rect) for the bar chart
var date = svg.selectAll(".date")
.data(dataset)
.enter()
.append("g")
.attr("class", "g")
.attr("transform", function(d) {return "translate(" + x0(d.date) + ",0)";});
/* Add field1 bars */
date.selectAll(".bar.field1")
.data(d => [d])
.enter()
.append("rect")
.attr("class", "bar field1")
.style("fill","blue")
.attr("x", d => x0(d.WorldPopulation))
.attr("y", d => y(d.WorldPopulation))
.attr("width", x1.bandwidth())
.attr("height", d => {
return height - margin.top - margin.bottom - y(d.WorldPopulation)
});
/* Add field2 bars */
date.selectAll(".bar.field2")
.data(d => [d])
.enter()
.append("rect")
.attr("class", "bar field2")
.style("fill","red")
.attr("x", d => x0(d.InternetUser))
.attr("y", d => y(d.InternetUser))
.attr("width", x1.bandwidth())
.attr("height", d => {
return height - margin.top - margin.bottom - y(d.InternetUser)
});
And this is my csv file. Not too sure how to upload excel so I took a screenshot.
Any help provided will be appreciated. Feel free to request for any extra snippets of my code for clarification.
edit: After tweaking the code, no errors are shown but the svg is not produced either.
Using scaleBand for both x0 and x1, the following code works:
<script src="js/d3.v4.js"></script>
<script>
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x0 = d3.scaleBand()
.rangeRound([0, width]).padding(.1);
var x1 = d3.scaleBand();
var y = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x0)
.tickSize(0);
var yAxis = d3.axisLeft()
.scale(y);
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("InternetUserStats.csv", function (error, data) {
var dates = data.map(function (d) { return d.date; });
var ymax = d3.max(data, function (d) { return Math.max(d.WorldPopulation, d.InternetUser); });
x0.domain(dates);
x1.domain(['WorldPopulations', 'InternetUsers']).rangeRound([0, x0.bandwidth()]);
y.domain([0, ymax]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var date = svg.selectAll(".g")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function (d) { return "translate(" + x0(d.date) + ",0)"; });
/* Add field1 bars */
date/*.selectAll(".bar.field1")
.data(data)
.enter()*/
.append("rect")
.attr("class", "bar field1")
.style("fill", "blue")
.attr("x", function (d) { return x1('WorldPopulations'); })
.attr("y", function (d) { return y(+d.WorldPopulation); })
.attr("width", x0.bandwidth() / 2)
.attr("height", function (d) {
return height /*- margin.top - margin.bottom*/ - y(d.WorldPopulation)
});
/* Add field2 bars */
date/*.selectAll(".bar.field1")
.data(data)
.enter()*/
.append("rect")
.attr("class", "bar field2")
.style("fill", "red")
.attr("x", function (d) { return x1('InternetUsers'); })
.attr("y", function (d) { return y(d.InternetUser); })
.attr("width", x0.bandwidth() / 2)
.attr("height", function (d) {
return height /*- margin.top - margin.bottom*/ - y(d.InternetUser)
});
});
</script>
EDIT: the following code adds a legend that is based on your comment and your second link:
//This code goes after field2 bars are added.
/* Legend */
var legend = svg.selectAll(".legend")
.data(['WorldPopulations', 'InternetUsers']) //Bind an array of the legend entries
.enter().append("g")
.attr("class", "legend")
.attr("font-family", "sans-serif")
.attr("font-size", 13)
.style("text-anchor", "end")
.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", function (d) {
// Return "blue" for "WorldPopulations" and "red" for "InternetUsers":
return ((d === "WorldPopulations") ? "blue" : "red");
});
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
//.style("text-anchor", "end") //Already applied to .legend
.text(function (d) { return d; });
I know this is easy and I saw some examples in this forum as well as other websites as well, but I simple can't figure it out.
I'm new in using D3 library to generate the charts. I'm trying to learn by creating bar chart.
My question is how to add the Data Labels into the chart?
Below is the codes I have.
then I have my JS:
var chartwidth = 800;
var chartheight = 600;
var data = [
{"Start_Dt":"Jan 15","UnitName":"Unit 1","ProgramName":"ProgramName 1","AttendCnt":159,"NewcomerCnt":10}
, {"Start_Dt":"Jan 22","UnitName":"Unit 2","ProgramName":"ProgramName 2","AttendCnt":178,"NewcomerCnt":5}
, {"Start_Dt":"Feb 14","UnitName":"Unit 2","ProgramName":"ProgramName 3","AttendCnt":240,"NewcomerCnt":46}
, {"Start_Dt":"Feb 19","UnitName":"Unit 1","ProgramName":"ProgramName 4","AttendCnt":201,"NewcomerCnt":10}
, {"Start_Dt":"Feb 26","UnitName":"Unit 2","ProgramName":"ProgramName 5","AttendCnt":177,"NewcomerCnt":7}
, {"Start_Dt":"Mar 12","UnitName":"Unit N","ProgramName":"ProgramName N","AttendCnt":184,"NewcomerCnt":3}
];
var margin = {top: 20, right: 20, bottom: 300, left: 40},
width = chartwidth - margin.left - margin.right,
height = chartheight - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
var formatTime = d3.time.format("%e %B");
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x2 = d3.scale.ordinal()
.rangeBands([0, width], 0);
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(".chart").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 + ")");
data.forEach(function(d) {
d.AttendCnt = +d.AttendCnt;
});
x.domain(data.map(function(d) { return d.Start_Dt + " " + d.ProgramName; }));
y.domain([0, d3.max(data, function(d) { return d.AttendCnt; })]);
//Create X Axis
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)" )
.append("text")
.attr("y", 25)
.attr("x",x.rangeBand()/2 )
.style("text-anchor", "middle")
.style("font-size", "20px")
.style("color", "black")
.text(function(d,i) { return "xxx"; });
//Create Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Attendance");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.Start_Dt + " " + d.ProgramName); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.AttendCnt); })
.attr("height", function(d) { return height - y(d.AttendCnt); });
Before
After
How to modify the codes to get the result I wanted? Tks
i haven't tested the code but it could be something like this :
svg.selectAll(".barText")
.data(data)
.enter().append("text")
.attr("class", "barText")
.attr("x", function(d) { return x(d.Start_Dt + " " + d.ProgramName); })
.attr("y", function(d) { return height - y(d.AttendCnt); })
.text(function(d) { return d.AttendCnt; })
;
Hope it helps
I want to assign two colors to two series in my data so that when I sort ascending or descending, the colors remain the same for each group.
The data is pulled programmatically from web map features. I thought I could get away with using an alternating function to assign colors but this doesn't work if I use sorting. I am trying to find a proper way to assign colors specifically to the series.
The data I am using has OL and NOL as two groups. You can see below how it is structured.
jsfiddle
relevant code:
var values = feature.properties;
var data = [
{name:"N11OL",value:values["N11OL"]},
{name:"N11NOL",value:values["N11NOL"]},
{name:"N21OL",value:values["N21OL"]},
{name:"N21NOL",value:values["N21NOL"]},
{name:"N22OL",value:values["N22OL"]},
{name:"N22NOL",value:values["N22NOL"]},
{name:"N23OL",value:values["N23OL"]},
{name:"N23NOL",value:values["N23NOL"]},
{name:"N31_33OL",value:values["N31_33OL"]},
{name:"N31_33NOL",value:values["N31_33NOL"]},
{name:"N41OL",value:values["N41OL"]},
{name:"N41NOL",value:values["N41NOL"]}
];
var Colors = ["#a6cee3", "#1f78b4"]
var margin = {top: 40, right: 2, bottom: 30, left: 180},
width = 400 - margin.left - margin.right,
height = 575 - margin.top - margin.bottom,
barHeight = height / data.length;
// Scale for X axis
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d){return d.value;})])
.range([0, width]);
var y = d3.scale.ordinal()
.domain(["NAICS11", "NAICS21", "NAICS22", "NAICS23", "NAICS31-33", "NAICS41"])
.rangeRoundBands([0, height]);
//y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.outerTickSize(0);
var svg = d3.select(div).select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.classed("chart", true);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = svg.selectAll("g.bar")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", function(d){return x(d.value);})
.attr("fill", function(d, i) {return Colors[i % 2]; }) //Alternate colors
.attr("height", barHeight - 1);
bar.append("text")
.attr("class", "text")
.attr("x", function(d) { return x(d.value) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d.value; })
.attr("fill", "white")
.attr("font-family", "sans-serif")
.attr("font-size", "14px")
.attr("text-anchor", "end");
svg.append("text")
.attr("class", "title")
.attr("x", width/7)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Employment by industry " + "(Total OL: " + feature.properties.IndOLTot + ")");
Starting at Line 241 in your jsFiddle
bar.append("rect")
.attr("width", function(d){return x(d.value);})
.attr("fill", function(d, i) {
if(d.name.indexOf("NOL") > -1) {
//return Colors[0];
return "red";
} else {
//return Colors[1];
return "black";
}
}) //Alternate colors
.attr("height", barHeight - 1);
This checks the name property for the substring "NOL". If the name contains "NOL" it uses the first color, if "NOL" is not found it uses the second color for a fill.
(I'm under the assumption that the series is determined by the name)
I have the following problems with my bar chart.How to set decimal label value in proper position in Bar graph.label should not be overlap in nearest bar.but in my case it's overlapping.please suggest how to correct it
below is my code
var data = [
{ Request: 1, AvgRequest: 4123.18 },
{ Request: 2, AvgRequest: 5221.16 },
{ Request: 3, AvgRequest: 32.42 },
{ Request: 4, AvgRequest: 22.13 },
{ Request: 5, AvgRequest: 413.21 },
{ Request: 6, AvgRequest: 112.19 }
];
var margin = { top: 40, right: 40, bottom: 35, left: 85 },
width = 450 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
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 + ")");
data.forEach(function (d) {
d.Request = d.Request;
d.AvgRequest = +d.AvgRequest;
});
x.domain(data.map(function (d) { return d.Request; }));
y.domain([0, d3.max(data, function (d) { return d.AvgRequest; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// xAxis label
svg.append("text")
.attr("transform", "translate(" + (width / 2) + " ," + (height + margin.bottom + 5) + ")")
.style("text-anchor", "middle")
.text("Numbers of request");
//yAxis label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("avg request);
// Title
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("Avg");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) { return x(d.Request); })
.attr("width", x.rangeBand())
.attr("y", function (d) { return y(d.AvgRequest); })
.attr("height", function (d) { return height - y(d.AvgRequest); });
var text = svg.selectAll("text1")
.data(data)
.enter()
.append("text")
.attr("class", function (d) { return "label " + d.Request; })
.attr("x", function (d, i) {
return x(i) + x.rangeBand() / 5;
})
.attr("y", function (d, i) {
return y(d.AvgRequest) + 25;
})
.text(function (d) { return d.AvgRequest; })
.attr("font-size", "15px")
.style("stroke", "black");
I added two new variables to separate dimensions of complete chart and plot area:
var margin = { top: 40, right: 40, bottom: 35, left: 85 },
width = 450,
height = 250;
plotAreaWidth = width - margin.left - margin.right,
plotAreaHeight = height - margin.top - margin.bottom;
and changed other code accordingly.
And changes for text labels:
var text = svg.selectAll("text1")
.data(data)
.enter()
.append("text")
.attr("class", function (d) { return "label " + d.Request; })
.attr("x", function (d, i) {
//return x(i) + x.rangeBand() / 2;
return x(d.Request);
})
.attr("y", function (d, i) {
//return y(d.AvgRequest) + 25;
return y(d.AvgRequest) - 5;
})
.text(function (d) { return d.AvgRequest; })
.attr("font-size", "15px")
.style("stroke", "black");
Changed example at jsbin.
I am creating a bar chart with d3.js from data stored in tsv file. I want to insert a text in each bar. How I can do?
I have tried even this solution, but doesn't work.
Here is the code of my function:
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, 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 + ")");
function visualize(file){
d3.tsv(file, function(error, data) {
data.forEach(function(d) {
d.weight = +d.weight;
});
x.domain(data.map(function(d) { return d.concept; }));
y.domain([0, d3.max(data, function(d) { return d.weight; })]);
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("weight");
svg.selectAll(".bar")
.data(data)
.enter().append("rect").style("fill", function (d){return d.color;})
.attr("class", "bar")
.attr("x", function(d) { return x(d.concept); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.weight); })
.attr("height", function(d) { return height - y(d.weight); });
svg.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) {
return d.concept;
})
.attr("text-anchor", "middle")
.attr("x", x)
.attr("y",y)
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
});
}
All my code with the files tsv are here: full code
AmeliaBR is right as usual, and I am only putting this answer because while I was working on it, I saw myself changing the code so that it really makes use of the Enter, Update, Exit selection paradigm. I have made quite a few changes in that regard. Here is the code, FWIW:
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, 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 + ")");
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("weight");
var g = svg.append("g");
function update(file){
d3.tsv(file, function(error, data) {
data.forEach(function(d) {
d.weight = +d.weight;
});
x.domain(data.map(function(d) { return d.concept; }));
y.domain([0, d3.max(data, function(d) { return d.weight; })]);
var bar = g.selectAll(".bar")
.data(data);
bar.enter()
.append("rect")
.attr("class","bar");
bar
.style("fill", function (d){return d.color;})
.attr("class", "bar")
.attr("x", function(d) { return x(d.concept); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.weight); })
.attr("height", function(d) { return height - y(d.weight); });
bar.exit().remove();
var text = g.selectAll(".text")
.data(data);
text.enter()
.append("text")
.attr("class","text");
text
.attr("text-anchor", "right")
.attr("x", function(d) { return x(d.concept); })
.attr("y", function(d) { return y(d.weight) + 22;})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white")
.text(function(d) {
return d.concept;
});
text.exit().remove();
});
}
And you call it like by doing update("data16.tsv") and then update("data15.tsv").
When you draw an axis, it creates separate <text> elements for each label inside the axis group inside the SVG. So if you then try to select all the <text> elements in the SVG, you're going to select all your axis labels. If you have more axis labels than data for text elements, your enter() selection will be empty and nothing will happen.
To be sure you're only selecting the correct <text> elements, give your text labels a class to distinguish them from the axis labels. And then use that class to narrow-down your selector:
svg.selectAll("text.bar-label")
.data(data)
.enter()
.append("text")
.attr("class", "bar-label")