Hi I am using D3 chart.
i'm using This d3 chart :http://bl.ocks.org/diethardsteiner/3287802
In this chart all the data are read from variable. I want to read the data from json file.
I have complete the half of the work. I did same to complete the another half of the work but it is not working.
Pie chart is read data from json. but the bar chart is not to read data from json.
Here I have Created Plunker check this and give some solution.
https://plnkr.co/edit/TaXMsUWuIXe5kv3yzazk?p=preview
here what i tried to read data is not read from json.
I want to run this chart as same as this example:http://bl.ocks.org/diethardsteiner/3287802
i tried like this
d3.json("data1.json", function(datasetBarChart){
debugger;
// set initial group value
var group = "All";
function datasetBarChosen(group) {
var ds = [];
for (x in datasetBarChart) {
if(datasetBarChart[x].group==group){
ds.push(datasetBarChart[x]);
}
}
return ds;
}
function dsBarChartBasics() {
debugger;
var margin = {top: 30, right: 5, bottom: 20, left: 50},
width = 500 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom,
colorBar = d3.scale.category20(),
barPadding = 1
;
return {
margin : margin,
width : width,
height : height,
colorBar : colorBar,
barPadding : barPadding
}
;
}
function dsBarChart() {
debugger;
var firstDatasetBarChart = datasetBarChosen(group);
var basics = dsBarChartBasics();
var margin = basics.margin,
width = basics.width,
height = basics.height,
colorBar = basics.colorBar,
barPadding = basics.barPadding
;
var xScale = d3.scale.linear()
.domain([0, firstDatasetBarChart.length])
.range([0, width])
;
var yScale = d3.scale.linear()
.domain([0, d3.max(firstDatasetBarChart, function(d) { return d.measure; })])
.range([height, 0])
;
//Create SVG element
var svg = d3.select("#barChart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("id","barChartPlot")
;
var plot = svg
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
;
plot.selectAll("rect")
.data(firstDatasetBarChart)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("width", width / firstDatasetBarChart.length - barPadding)
.attr("y", function(d) {
return yScale(d.measure);
})
.attr("height", function(d) {
return height-yScale(d.measure);
})
.attr("fill", "lightgrey")
;
// Add y labels to plot
plot.selectAll("text")
.data(firstDatasetBarChart)
.enter()
.append("text")
.text(function(d) {
return formatAsInteger(d3.round(d.measure));
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return (i * (width / firstDatasetBarChart.length)) + ((width / firstDatasetBarChart.length - barPadding) / 2);
})
.attr("y", function(d) {
return yScale(d.measure) + 14;
})
.attr("class", "yAxis")
var xLabels = svg
.append("g")
.attr("transform", "translate(" + margin.left + "," + (margin.top + height) + ")")
;
debugger;
xLabels.selectAll("text.xAxis")
.data(firstDatasetBarChart)
.enter()
.append("text")
.text(function(d) { return d.category;})
.attr("text-anchor", "middle")
// Set x position to the left edge of each bar plus half the bar width
.attr("x", function(d, i) {
return (i * (width / firstDatasetBarChart.length)) + ((width / firstDatasetBarChart.length - barPadding) / 2);
})
.attr("y", 15)
.attr("class", "xAxis")
//.attr("style", "font-size: 12; font-family: Helvetica, sans-serif")
;
// Title
svg.append("text")
.attr("x", (width + margin.left + margin.right)/2)
.attr("y", 15)
.attr("class","title")
.attr("text-anchor", "middle")
.text("Elevator Trips by Material Stream and Destination")
;
}
dsBarChart();
/* ** UPDATE CHART ** */
/* updates bar chart on request */
function updateBarChart(group, colorChosen) {
debugger;
var currentDatasetBarChart = datasetBarChosen(group);
var basics = dsBarChartBasics();
var margin = basics.margin,
width = basics.width,
height = basics.height,
colorBar = basics.colorBar,
barPadding = basics.barPadding
;
var xScale = d3.scale.linear()
.domain([0, currentDatasetBarChart.length])
.range([0, width])
;
var yScale = d3.scale.linear()
.domain([0, d3.max(currentDatasetBarChart, function(d) { return d.measure; })])
.range([height,0])
;
var svg = d3.select("#barChart svg");
var plot = d3.select("#barChartPlot")
.datum(currentDatasetBarChart)
;
/* Note that here we only have to select the elements - no more appending! */
plot.selectAll("rect")
.data(currentDatasetBarChart)
.transition()
.duration(750)
.attr("x", function(d, i) {
return xScale(i);
})
.attr("width", width / currentDatasetBarChart.length - barPadding)
.attr("y", function(d) {
return yScale(d.measure);
})
.attr("height", function(d) {
return height-yScale(d.measure);
})
.attr("fill", colorChosen)
;
plot.selectAll("text.yAxis") // target the text element(s) which has a yAxis class defined
.data(currentDatasetBarChart)
.transition()
.duration(750)
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return (i * (width / currentDatasetBarChart.length)) + ((width / currentDatasetBarChart.length - barPadding) / 2);
})
.attr("y", function(d) {
return yScale(d.measure) + 14;
})
.text(function(d) {
return formatAsInteger(d3.round(d.measure));
})
.attr("class", "yAxis")
;
svg.selectAll("text.title") // target the text element(s) which has a title class defined
.attr("x", (width + margin.left + margin.right)/2)
.attr("y", 15)
.attr("class","title")
.attr("text-anchor", "middle")
.text(group + "'s Elevator Trips by Material Stream and Destination")
;
}
});
Thanks,
You are using wrong d3.json callback signature. The first argument of the callback is an error that occurred, or null if no error occurred, the second argument is the returned data. So, you should use following:
d3.json("data1.json", function(error, data){
if(error) {
// handle error
} else {
// work with the data array
}
}
The following code snippet demonstrates the loading of dataset from an external JSON storage. When data has been loaded it is passed to the dsPieChart function that draws the above mentioned pie chart.
d3.select(window).on('load', function() {
// Loading data from external JSON source
d3.json('https://api.myjson.com/bins/1hewit', function(error, json) {
if (error) {
throw new Error('An error occurs');
} else {
dsPieChart(json);
}
});
});
// Format options
var formatAsPercentage = d3.format("%"),
formatAsPercentage1Dec = d3.format(".1%"),
formatAsInteger = d3.format(","),
fsec = d3.timeFormat("%S s"),
fmin = d3.timeFormat("%M m"),
fhou = d3.timeFormat("%H h"),
fwee = d3.timeFormat("%a"),
fdat = d3.timeFormat("%d d"),
fmon = d3.timeFormat("%b");
// PIE CHART drawing
function dsPieChart(dataset) {
var width = 400,
height = 400,
outerRadius = Math.min(width, height) / 2,
innerRadius = outerRadius * .999,
innerRadiusFinal = outerRadius * .5,
innerRadiusFinal3 = outerRadius * .45,
color = d3.scaleOrdinal(d3.schemeCategory20);
var vis = d3.select("#pieChart")
.append("svg:svg")
.data([dataset])
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
var arc = d3.arc()
.outerRadius(outerRadius).innerRadius(innerRadius);
var arcFinal = d3.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius);
var arcFinal3 = d3.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius);
var pie = d3.pie()
.value(function(d) {
return d.measure;
});
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", up);
arcs.append("svg:path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc)
.append("svg:title")
.text(function(d) {
return d.data.category + ": " + formatAsPercentage(d.data.measure);
});
d3.selectAll("g.slice").selectAll("path").transition()
.duration(750)
.delay(10)
.attr("d", arcFinal);
arcs.filter(function(d) {
return d.endAngle - d.startAngle > .2;
})
.append("svg:text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")";
})
.text(function(d) {
return d.data.category;
});
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
vis.append("svg:text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text("Revenue Share 2012")
.attr("class", "title");
function mouseover() {
d3.select(this).select("path").transition()
.duration(750)
.attr("d", arcFinal3);
}
function mouseout() {
d3.select(this).select("path").transition()
.duration(750)
.attr("d", arcFinal);
}
function up(d, i) {
updateBarChart(d.data.category, color(i));
updateLineChart(d.data.category, color(i));
}
}
#pieChart {
position: absolute;
top: 10px;
left: 10px;
width: 400px;
height: 400px;
}
.slice {
font-size: 12pt;
font-family: Verdana;
fill: white;
font-weight: bold;
}
.title {
font-family: Verdana;
font-size: 15px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="pieChart"></div>
See also Bar chart from external JSON file example.
Related
I have made a D3 histogram look responsive but I want it to be 100% responsive on any screen (div) resize. I think the idea is to calculate the diagonal of the parent div and use that to change the axis length accordingly. In this case below, The said idea calculates the horizontal size but I can not get it to recognize a vertical length and that messes up the horizontal resize.
var color = "steelblue";
// Generate a 1000 data points using normal distribution with mean=20, deviation=5
var values = d3.range(1000).map(d3.random.normal(20, 5));
//var values = {{data}}
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {
top: 30,
right: 5,
bottom: 20,
left: 5
},
width = parseInt(d3.select("#histog").style("width")) - margin.left - margin.right
height = 275 - margin.top - margin.bottom;
var max = d3.max(values);
var min = d3.min(values);
var x = d3.scale.linear()
.domain([min, max])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
var yMax = d3.max(data, function(d) {
return d.length
});
var yMin = d3.min(data, function(d) {
return d.length
});
var colorScale = d3.scale.linear()
.domain([yMin, yMax])
.range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);
var y = d3.scale.linear()
.domain([0, yMax])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bOkottom");
var svg = d3.select("#histog").append("svg")
.attr("width", "100%")
.attr("height", "26vh")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) {
return "translate(" + x(d.x) + "," + y(d.y) + ")";
});
bar.append("rect")
.attr("x", 1)
.attr("width", (x(data[0].dx) - x(0)) - 1)
.attr("height", function(d) {
return height - y(d.y);
})
.attr("fill", function(d) {
return colorScale(d.y)
});
bar.append("text")
.attr("dy", ".75em")
.attr("y", -12)
.attr("x", (x(data[0].dx) - x(0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) {
return formatCount(d.y);
});
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
/*
* Adding refresh method to reload new data
*/
function refresh(values) {
// var values = d3.range(1000).map(d3.random.normal(20, 5));
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
// Reset y domain using new data
var yMax = d3.max(data, function(d) {
return d.length
});
var yMin = d3.min(data, function(d) {
return d.length
});
y.domain([0, yMax]);
var colorScale = d3.scale.linear()
.domain([yMin, yMax])
.range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);
var bar = svg.selectAll(".bar").data(data);
// Remove object with data
bar.exit().remove();
bar.transition()
.duration(1000)
.attr("transform", function(d) {
return "translate(" + x(d.x) + "," + y(d.y) + ")";
});
bar.select("rect")
.transition()
.duration(1000)
.attr("height", function(d) {
return height - y(d.y);
})
.attr("fill", function(d) {
return colorScale(d.y)
});
bar.select("text")
.transition()
.duration(1000)
.text(function(d) {
return formatCount(d.y);
});
}
.histocontainer {
float: right;
width: 55%;
margin-right: auto;
margin-left: auto;
text-align: top;
}
#media (min-width: 576px) {
.histocontainer {
max-width: 540px;
}
}
#media (min-width: 768px) {
.histocontainer {
max-width: 720px;
}
}
#media (min-width: 992px) {
.histocontainer {
max-width: 960px;
}
}
#media (min-width: 1200px) {
.histocontainer {
max-width: 1140px;
}
}
#scalesvg {
width: 20%;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<svg id="scalesvg">
<div id=histog></div>
</svg>
I've simplified the example a bit and used the structure of your refresh function to create a resize function. I use window.addEventListener("resize") to detect resizes and trigger the function.
All the stuff that can be done without knowing the width and height, I do outside the function, and inside I just redraw the bins and the axis.
It's all your code, I just moved it around a little.
var color = "steelblue";
// Generate a 1000 data points using normal distribution with mean=20, deviation=5
var values = d3.range(1000).map(d3.random.normal(20, 5));
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {
top: 30,
right: 5,
bottom: 20,
left: 5
};
var max = d3.max(values);
var min = d3.min(values);
var x = d3.scale.linear()
.domain([min, max]);
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
var yMax = d3.max(data, function(d) {
return d.length
});
var yMin = d3.min(data, function(d) {
return d.length
});
var colorScale = d3.scale.linear()
.domain([yMin, yMax])
.range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);
var y = d3.scale.linear()
.domain([0, yMax]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var svg = d3.select("svg")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis");
function resize() {
var rect = d3.select('svg').node().getBoundingClientRect();
var width = rect.width - margin.left - margin.right;
var height = Math.min(rect.height, window.innerHeight) - margin.top - margin.bottom;
x.range([0, width]);
y.range([height, 0]);
// Reposition elements
svg.select('x.axis')
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var bar = svg.selectAll(".bar").data(data);
// Remove object with data
bar.exit().remove();
var newBars = bar.enter()
.append("g")
.attr("class", "bar");
newBars.append("rect")
.attr("x", 1);
newBars.append("text")
.attr("dy", ".75em")
.attr("y", -12)
.attr("text-anchor", "middle")
bar.transition()
.duration(1000)
.attr("transform", function(d) {
return "translate(" + x(d.x) + "," + y(d.y) + ")";
});
bar.select("rect")
.transition()
.duration(1000)
.attr("width", (x(data[0].dx) - x(0)) - 1)
.attr("height", function(d) {
return height - y(d.y);
})
.attr("fill", function(d) {
return colorScale(d.y);
});
bar.select("text")
.transition()
.duration(1000)
.attr("x", (x(data[0].dx) - x(0)) / 2)
.text(function(d) {
return formatCount(d.y);
});
}
window.addEventListener("resize", function() {
console.log('resize!');
resize();
});
resize();
svg {
float: left;
width: 100%;
height: 300px;
margin-right: auto;
margin-left: auto;
text-align: top;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<svg></svg>
I am trying to create two heatmaps showing different data updated by a common date drop down. I am using heatmap with data update and creating two separate svgs to update when a new date field is selected in the dropdown. I was able to follow some of the SO answers to create two plots in the same page, but I am totally clueless as to have just one drop down of the locations update both charts simultaneously. Any pointers on how to achieve this would be greatly appreciated. I have included the code I have been working with and the json data. I have the data in two different files for now. Would be even better if it can be just from one file to make it easier to read the location dropdown value.
var dataset;
var dataset2;
var days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
times = d3.range(24);
var margin = {top:40, right:50, bottom:70, left:50};
// calculate width and height based on window size
var w = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,
gridSize = Math.floor(w / times.length),
h = gridSize * (days.length+2);
//reset the overall font size
var newFontSize = w * 62.5 / 900;
d3.select("html").style("font-size", newFontSize + "%");
// svg container
var svg = d3.select("#heatmap")
.append("svg")
.attr("width", w + margin.top + margin.bottom)
.attr("height", h + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// svg container
var svg2 = d3.select("#heatmap2")
.append("svg")
.attr("width", w + margin.top + margin.bottom)
.attr("height", h + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// linear colour scale
var colours = d3.scaleLinear()
.domain(d3.range(1, 11, 1))
.range(["#87cefa", "#86c6ef", "#85bde4", "#83b7d9", "#82afce", "#80a6c2", "#7e9fb8", "#7995aa", "#758b9e", "#708090"]);
var dayLabels = svg.selectAll(".dayLabel")
.data(days)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", 0)
.attr("y", function(d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
var dayLabels = svg2.selectAll(".dayLabel")
.data(days)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", 0)
.attr("y", function(d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)");
var timeLabels = svg2.selectAll(".timeLabel")
.data(times)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)");
// load data heatmap 1
d3.json("test.json", function(error, data) {
data.forEach(function(d) {
d.day = +d.day;
d.hour = +d.hour;
d.value = +d.value;
});
dataset = data;
// group data by location
var nest = d3.nest()
.key(function(d) { return d.location; })
.entries(dataset);
// array of locations in the data
var locations = nest.map(function(d) { return d.key; });
var currentLocationIndex = 0;
// create location dropdown menu
var locationMenu = d3.select("#locationDropdown1");
locationMenu
.append("select")
.attr("id", "locationMenu")
.selectAll("option")
.data(locations)
.enter()
.append("option")
.attr("value", function(d, i) { return i; })
.text(function(d) { return d; });
// function to create the initial heatmap
var drawHeatmap = function(location) {
// filter the data to return object of location of interest
var selectLocation = nest.find(function(d) {
return d.key == location;
});
var heatmap = svg.selectAll(".hour")
.data(selectLocation.values)
.enter()
.append("rect")
.attr("x", function(d) { return (d.hour-1) * gridSize; })
.attr("y", function(d) { return (d.day-1) * gridSize; })
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("stroke", "white")
.style("stroke-opacity", 0.6)
.style("fill", function(d) { return colours(d.value); })
}
drawHeatmap(locations[currentLocationIndex]);
var updateHeatmap = function(location) {
// filter data to return object of location of interest
var selectLocation = nest.find(function(d) {
return d.key == location;
});
// update the data and redraw heatmap
var heatmap = svg.selectAll(".hour")
.data(selectLocation.values)
.transition()
.duration(500)
.style("fill", function(d) { return colours(d.value); })
}
// run update function when dropdown selection changes
locationMenu.on("change", function() {
// find which location was selected from the dropdown
var selectedLocation = d3.select(this)
.select("select")
.property("value");
currentLocationIndex = +selectedLocation;
// run update function with selected location
updateHeatmap(locations[currentLocationIndex]);
});
})
// load data heatmap 2
d3.json("test2.json", function(error, data2) {
data2.forEach(function(d2) {
d2.day = +d2.day;
d2.hour = +d2.hour;
d2.value = +d2.value;
});
dataset2 = data2;
// group data by location
var nest2 = d3.nest()
.key(function(d2) { return d2.location; })
.entries(dataset2);
// array of locations in the data
var locations2 = nest2.map(function(d2) { return d2.key; });
var currentLocationIndex2 = 0;
// create location dropdown menu
var locationMenu2 = d3.select("#locationDropdown2");
locationMenu2
.append("select")
.attr("id", "locationMenu")
.selectAll("option")
.data(locations2)
.enter()
.append("option")
.attr("value", function(d2, i2) { return i2; })
.text(function(d2) { return d2; });
// function to create the initial heatmap
var drawHeatmap2 = function(location2) {
// filter the data to return object of location of interest
var selectLocation2 = nest2.find(function(d2) {
return d2.key == location2;
});
var heatmap2 = svg2.selectAll(".hour")
.data(selectLocation2.values)
.enter()
.append("rect")
.attr("x", function(d2) { return (d2.hour-1) * gridSize; })
.attr("y", function(d2) { return (d2.day-1) * gridSize; })
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("stroke", "white")
.style("stroke-opacity", 0.6)
.style("fill", function(d2) { return colours(d2.value); })
}
drawHeatmap2(locations2[currentLocationIndex2]);
var updateHeatmap2 = function(location2) {
console.log("currentLocationIndex: " + currentLocationIndex2)
// filter data to return object of location of interest
var selectLocation2 = nest2.find(function(d2) {
return d2.key == location2;
});
// update the data and redraw heatmap
var heatmap2 = svg2.selectAll(".hour")
.data(selectLocation2.values)
.transition()
.duration(500)
.style("fill", function(d2) { return colours(d2.value); })
}
// run update function when dropdown selection changes
locationMenu2.on("change", function() {
// find which location was selected from the dropdown
var selectedLocation2 = d3.select(this)
.select("select")
.property("value");
currentLocationIndex2 = +selectedLocation2;
// run update function with selected location
updateHeatmap2(locations2[currentLocationIndex2]);
});
})
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
html {
font-size: 62.5%;
}
body {
margin-top: 30px;
font-size: 1.4rem;
font-family: 'Source Sans Pro', sans-serif;
font-weight: 400;
fill: #696969;
text-align: center;
}
.timeLabel, .dayLabel {
font-size: 1.6rem;
fill: #AAAAAA;
font-weight: 300;
}
#nav-container {
display: flex;
justify-content: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="nav-container">
<div id="locationDropdown1"></div>
</div>
<div id="heatmap"></div>
<div id="nav-container">
<div id="locationDropdown2"></div>
</div>
<div id="heatmap2"></div>
JSON sample is the same as the link above .. just with some values modified to show differentiation. (Not sure how to include a big json file on here). Thanks again.
Ive been at this for hours and cant seem to get my grouped bar chart to behave. Specifically trying to obtain a proper width for the 'g' translate property around each bar.
I have tried multiple methods and this seems to be the most elegant although im open to other solutions. The goal is something like this: http://www.cagrimmett.com/til/2016/04/26/responsive-d3-bar-chart.html
var data = [{"category":"Securily Provisions","values":[{"value":50,"rate":"Work Performed"},{"value":40,"rate":"Knowledge, Skills, and Abilities"}]},{"category":"Investigate","values":[{"value":25,"rate":"Work Performed"},{"value":21,"rate":"Knowledge, Skills, and Abilities"}]},{"category":"Operate and Maintain","values":[{"value":3,"rate":"Work Performed"},{"value":22,"rate":"Knowledge, Skills, and Abilities"}]},{"category":"Oversee and Govern","values":[{"value":12,"rate":"Work Performed"},{"value":7,"rate":"Knowledge, Skills, and Abilities"}]},{"category":"Protect and Defend","values":[{"value":6,"rate":"Work Performed"},{"value":15,"rate":"Knowledge, Skills, and Abilities"}]},{"category":"Collect and Operate","values":[{"value":92,"rate":"Work Performed"},{"value":85,"rate":"Knowledge, Skills, and Abilities"}]}]
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 ;
var x0 = d3.scale.ordinal().rangeRoundBands([0, width], .5);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var color = d3.scale.ordinal()
.range(["#02bfe7","#fdb81e"]);
var svg = d3.select('#chart-area').append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("preserveAspectRatio", "xMinYMin meet")
.append("g").attr("class","container")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.json("data.json", function(error, data) {
var categoriesNames = data.map(function(d) {
return d.category;
});
var rateNames = data[0].values.map(function(d) {
return d.rate;
});
x0.domain(categoriesNames);
x1.domain(rateNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(categorie) {
return d3.max(categorie.values, function(d) {
return d.value;
});
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.style('opacity','0')
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style('font-weight','bold')
.text("Value");
svg.select('.y').transition().duration(500).delay(1300).style('opacity','1');
var slice = svg.selectAll(".slice")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform",function(d) { return "translate(" + x0(d.category) + ",0)"; });
slice.selectAll("rect")
.data(function(d) { return d.values; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.rate); })
.style("fill", function(d) { return color(d.rate) })
.attr("y", function(d) { return y(0); })
.attr("height", function(d) { return height - y(0); })
.on("mouseover", function(d) {
d3.select(this).style("fill", d3.rgb(color(d.rate)).darker(2));
})
.on("mouseout", function(d) {
d3.select(this).style("fill", color(d.rate));
});
slice.selectAll("rect")
.transition()
.delay(function (d) {return Math.random()*1000;})
.duration(1000)
.attr("class","bar")
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });
//Legend
var legend = svg.selectAll(".legend")
.data(data[0].values.map(function(d) { return d.rate; }).reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d,i) { return "translate(0," + i * 20 + ")"; })
.style("opacity","0");
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d) { return color(d); });
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) {return d; });
legend.transition().duration(500).delay(function(d,i){ return 1300 + 100 * i; }).style("opacity","1");
document.addEventListener("DOMContentLoaded", resize);
d3.select(window).on('resize', resize);
function resize() {
console.log('----resize function----');
// update width
width = parseInt(d3.select('#chart-area').style('width'), 10);
width = width - margin.left - margin.right;
height = parseInt(d3.select("#chart-area").style("height"));
height = height - margin.top - margin.bottom;
console.log('----resiz width----'+width);
console.log('----resiz height----'+height);
// resize the chart
x0.range([0, width]);
x0.rangeRoundBands([0, width], .03);
y.range([height, 0]);
yAxis.ticks(Math.max(height/50, 2));
xAxis.ticks(Math.max(width/50, 2));
d3.select(svg.node().parentNode)
.style('width', (width + margin.left + margin.right) + 'px');
svg.selectAll('.g')
//.attr("x", function(d) { return x0(categoriesNames); })
//.attr("x", function(d) { return x1(d.rate); })
// Problem here applying new width within translate
.attr("transform", "translate(10,0)")
.attr("width", x1.rangeBand());
svg.selectAll("text")
// .attr("x", function(d) { return x0(categoriesNames); })
.attr("x", (function(d) { return x0(categoriesNames ) + x0.rangeBand() / 2 ; } ))
.attr("y", function(d) { return y(rateNames) + 1; })
.attr("dy", ".75em");
svg.select('.x.axis').call(xAxis.orient('bottom')).selectAll("text").attr("x",55);
}
//});
.bar{
fill: steelblue;
}
.bar:hover{
fill: brown;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
#chart-area {width: 100%;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="chart-area"></div>
Here's a solution. Is this the desired output? Try resizing the window.
JS FIDDLE
Resize function:
function resize() {
console.log('----resize function----');
// update width
width = parseInt(d3.select('#chart-area').style('width'), 10);
width = width - margin.left - margin.right;
height = parseInt(d3.select("#chart-area").style("height"));
height = height - margin.top - margin.bottom;
console.log('----resiz width----'+width);
console.log('----resiz height----'+height);
// resize the chart
x0.rangeRoundBands([0, width], .5);
x1.domain(rateNames).rangeRoundBands([0, x0.rangeBand()]);
y.range([height, 0]);
yAxis.ticks(Math.max(height/50, 2));
xAxis.ticks(Math.max(width/50, 2));
d3.select(svg.node().parentNode)
.style('width', (width + margin.left + margin.right) + 'px');
svg.selectAll('.g')
.attr("transform",function(d) {
return "translate(" + x0(d.category) + ",0)";
});
svg.selectAll('.g').selectAll("rect").attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.rate); })
svg.selectAll(".legend rect")
.attr("x", width - 18);
svg.selectAll('.legend text')
.attr("x", width - 24)
svg.select('.x.axis').call(xAxis.orient('bottom'));
}
I made a few changes to the resize function. Here's why:
x0 and x1 ranges (both) have to be reset on resize:
x0.rangeRoundBands([0,width],.5);
x1.domain(rateNames).rangeRoundBands([0,x0.rangeBand()]);
y.range([height, 0]);
Translate of (10,0) was being force set in the resize function and you cannot apply width to a (group).
Basically, you just need to call all the code from the original render that includes width and height changes. Take a look at the resize function.
Re-rendering X-axis at the bottom included a static value for the x ticks:
svg.select('.x.axis').call(xAxis.orient('bottom')).selectAll("text").attr("x",55);
Just removed the attr("x", 55)
Hope this helps. :)
I am building up a grouped bar chart. In the chart, I want to color one group of bar chart differently because its Missouri number is bigger than the national average number. However, my else if statement doesn't work out for the fill function. Can anyone tell me what should I do to color the chart differently based on the comparison of numbers? Thanks in advance!!
Here is my Code
<svg id="bodychart" width="900" height="500" style="display: block; margin: auto"></svg>
<script>
var svg = d3.select("#bodychart"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top +")" ); //Not quite understand (??)
var x0 = d3.scaleBand()
.rangeRound([0, width])
.paddingInner(0.1);
var x1 = d3.scaleBand()
.padding(0.05);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var z = d3.scaleOrdinal()
.range(["#F63014", "#ABABAB"]);
var tooltip = d3.select("body").append("div").attr("class", "toolTip");
d3.csv("number.csv", function(d, i, columns){
for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = + d[columns[i]];
return d;
}, function(error, data) {
if (error) throw error;
var keys = data.columns.slice(1);
x0.domain(data.map(function(d) {return d.BodyParts; }));
x1.domain(keys).rangeRound([0, x0.bandwidth()]);
y.domain([0, d3.max(data, function(d) {return d3.max(keys, function(key) {return d[key]; }); })]);
g.append("g")
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d) {return "translate(" + x0(d.BodyParts) + ",0)"; })
.selectAll("rect")
.data(function(d) {return keys.map(function(key){return {key: key, value: d[key]}; }); })
.enter()
.append("rect")
.attr("x", function(d) {return x1(d.key);})
.attr("y", function(d) {return y(d.value);})
.attr("width", x1.bandwidth())
.attr("height", function(d){return height - y(d.value);})
.attr("fill", function(d, i) {
if (d.value['Missouri'] > d.value['National_Average']) {
return z(d.key);
} else (d.value['Missouri'] < d.value['National_Average']) {
return "yellow";
}
})
.on("mousemove", function(d){
tooltip
.style("left", d3.event.pageX - 50 + "px")
.style("top", d3.event.pageY - 70 + "px")
.style("display", "inline-block")
.html("<span style='font-weight: bold'>"+ (d.key) +"</span>" + ":" + "<br>" + "$" + d3.format(",.0f")(d.value));
})
.on("mouseout", function(d){ tooltip.style("display", "none");});
g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x0));
g.append("g")
.attr("class", "axis")
.call(d3.axisLeft(y).ticks(10, ",.0f"))
.append("text")
.attr("x", -32)
.attr("y", y(y.ticks().pop()) + 0.5)
.attr("dy", "-3em")
.attr("fill", "#000")
.attr("font-weight", "bold")
.attr("text-anchor", "start")
.text("Dollars");
});
Here is my csv file:
BodyParts,Missouri,National_Average
Arm,115100,169878
Leg,102697,153221
Hand,86821,144930
Thumb,29767,42432
Index Finger,22325,24474
Middle Finger,17364,20996
Ring Finger,17364,14660
Pinky,10915,11343
Foot,74418,91779
Big Toe,19845,23436
Eye,69457,96700
Ear,24310,38050
Testicle,0,27678
Since the complete data for each pair lies in the parent selection, you have to get it before doing any comparison.
Thus, when setting the fill for each bar, this...
var parentData = d3.select(this.parentNode).data()[0];
... will store the data for the pair, that is, Missouri and National_Average.
Then, use that object to fill the bars conditionally. This is a way to do that (there are shorter ways, of course, but I believe this verbose snippet is more didactic for you):
.attr("fill", function(d, i) {
var parentData = d3.select(this.parentNode).data()[0];
if (d.key === "Missouri") {
if (parentData.Missouri > parentData.National_Average) {
return "green"
} else {
return "red"
}
} else {
if (parentData.Missouri < parentData.National_Average) {
return "green"
} else {
return "red"
}
}
})
Here is a plunker showing it: http://plnkr.co/edit/dfjKFUpuiJvLs6wWkO99?p=preview
Note In this question, I asked how to add a distribution line to the chart.
This is my current status:
I don’t quite understand how to plot two distributions curves for the histograms. Like this:
This is my code (using D3.js version 4):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.bar1 rect {
fill: rgba(0,0,255,0.6);
}
.bar1:hover rect{
fill: rgba(0,0,255,0.9);
}
.bar1 text {
fill: #fff;
font: 10px sans-serif;
}
.bar2 rect {
fill: rgba(255,0,0,0.6);
}
.bar2:hover rect{
fill: rgba(255,0,0,0.9);
}
.bar2 text {
fill: #fff;
font: 10px sans-serif;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
function draw(data) {
var allCongruentData = data.map(function(e){ return e.Congruent;});
var allIncongruentData = data.map(function(e){ return e.Incongruent;});
var formatCount = d3.format(",.0f");
var svg = d3.select("svg"),
margin = {top: 10, right: 30, bottom: 30, left: 30},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.rangeRound([0, width])
.domain([8, 36]);
var bins1 = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(40))
(allCongruentData);
// var curve = d3.line()
// .x(function(d) { return ???; })
// .y(function(d) { return y(d.Congruent); })
// .curve(d3.curveCatmullRom.alpha(0.5));
var bins2 = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(40))
(allIncongruentData);
var y = d3.scaleLinear()
.domain([0, d3.max(bins1, function(d) { return d.length; })])
.range([height, 0]);
var bar1 = g.selectAll(".bar1")
.data(bins1)
.enter().append("g")
.attr("class", "bar1")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar1.append("rect")
.attr("x", 0.5)
.attr("width", x(bins1[0].x1) - x(bins1[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
var bar2 = g.selectAll(".bar2")
.data(bins2)
.enter().append("g")
.attr("class", "bar2")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar2.append("rect")
.attr("x", 0.5)
.attr("width", x(bins2[0].x1) - x(bins2[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
bar1.append("text")
.attr("dy", ".75em") // why?
.attr("y", 6)
.attr("x", (x(bins1[0].x1) - x(bins1[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
bar2.append("text")
.attr("dy", ".75em") // why?
.attr("y", 6)
.attr("x", (x(bins2[0].x1) - x(bins2[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var legend = svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(" + (width - 245) + "," + 40 + ")")
.selectAll("g")
.data(["Congruent", "Incongruent"])
.enter().append("g");
legend.append("text")
.attr("y", function(d, i) {
return i * 30 + 5;
})
.attr("x", 200)
.text(function(d) {
return d;
});
legend.append("rect")
.attr("y", function(d, i) {
return i * 30 - 8;
})
.attr("x", 167)
.attr("width", 20)
.attr("height", 20)
.attr("fill", function(d) {
if (d == "Congruent") {
return 'rgba(0,0,255,0.6';
} else {
return 'rgba(255,0,0,0.6';
}
});
// g.append("path")
// .datum(data)
// .attr("d", line);
}
</script>
</head>
<body>
<h1>Stroop Test</h1>
<svg width="960" height="500"></svg>
<script type="text/javascript">
d3.csv("stroopdata.csv", function(d) {
d.Congruent = +d.Congruent;
d.Incongruent = +d.Incongruent;
return d;
}, draw);
</script>
</body>
</html>
The data looks like this:
Congruent,Incongruent
12.079,19.278
16.791,18.741
9.564,21.214
8.630,15.687
14.669,22.803
12.238,20.878
14.692,24.572
8.987,17.394
9.401,20.762
14.480,26.282
22.328,24.524
15.298,18.644
15.073,17.510
16.929,20.330
18.200,35.255
12.130,22.158
18.495,25.139
10.639,20.429
11.344,17.425
12.369,34.288
12.944,23.894
14.233,17.960
19.710,22.058
16.004,21.157
Any help appreciated.