Bar charts are not being displayed in SVG - d3.js

I am learning D3, i am trying to create a bar chart , But i couldn't find where the issue is but my bar chart is not being displayed in svg.
Below is my code , a html file,js file and my csv data
This is to create bar graph.
I have no clue what is it that I am missing.
I can see the svg area in the browser but not the graph.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<title>Gapminder Clone</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Custom styling -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
</div>
</nav>
<!-- Bootstrap grid setup -->
<div class="container">
<div class="row">
<div id="chart-area"></div>
</div>
</div>
<!-- External JS libraries -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>-->
<script src="js/d3.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
main.js
------------------
/*
* main.js
* Mastering Data Visualization with D3.js
* 2.5 - Activity: Adding SVGs to the screen
*/
document.addEventListener('DOMContentLoaded', function(e) {
var data=d3.csv("expenditure.csv").then(function(data){
data.forEach(function(d){
d.Budget= +d.Budget;
d.Year= +d.Year;
})
});
var margin= {
top:30,
bottom:30,
right:30,
left:30
};
var width = 800-margin.left-margin.right;
var height = 300-margin.top-margin.bottom;
var x = d3.scaleLinear()
.domain([2000,90000])
.range([0,width]);
var y = d3.scaleLinear()
.domain([0,8])
.range([0,height]);
var svg = d3.select("#chart-area")
.append("svg")
.attr("width", 700 + margin.left + margin.right)
.attr("height", 200 + margin.top + margin.bottom)
.attr("transform", "translate(" + margin.left +
", " + margin.top + ")");
var rects = svg.selectAll("rect").data(data);
rects.enter().append("rect")
.attr("x",0)
.attr("y",function(d,i) {
return y(i);
})
.attr("width",function(d){
if(d.Country=="France"){
return x(d.Budget);
}else {
return x(d.Budget);
}
})
.attr("height",function(d,i) {
return y(1)-8;
})
.attr("fill",function(d){
if(d.Country=="Australia")
{
return "yellow";
}else if(d.Country=="Canada"){
return "green";
}else if(d.Country=="Brazil"){
return "Orange";
}else {
return "blue";
}
})
rects.enter().append("text")
//.classed("bar-label",true)
.attr("x",function(d,i) {
return x(d.Budget);
})
.attr("dx",3)
.attr("y",function(d,i) {
return y(i);
})
.attr("dy",function(d,i) {
return y(1)/1.5-5;
})
.text(function(d,i) {
return d.Budget;
})
});
Expenditure.csv
-------------------------------
Country,Year,Budget
Australia,1990,6704
Australia,2014,25784
Brazil,1990,9236
Brazil,2014,32660
Canada,1990,11415
Canada,2014,17854
France,1990,42590
France,2014,63614

You have a typo in your code.
In the main.js file, on line 11:
var data=d3.csv("expenditure.csv").then(function(data){
data.forEach(function(d){
d.Budget= +d.Budget;
d.Year= +d.Year;
//})
});
You should take the }) brakets where commented and put them at the end of the file. After that it works perfectly.

Related

D3.js - X-axis not appearing on Scatterplot

I am trying to build a scatterplot by loading data from a .csv file. My scatterplot is trying to show Poverty (x-axis) vs. Healthcare (y-axis) for each state.
Here's a snippet of the CSV file:
id state healthcare poverty
1 Alabama 13.9 19.3
2 Alaska 11.2 11.4
3 Arizona 14.4 18.2
4 Arkansas 16.3 18.9
5 California 14.8 16.4
6 Colorado 12.8 12
7 Connecticut 8.7 10.8
8 Delaware 8.7 12.5
Here's my javascript code:
var svgWidth = 960;
var svgHeight = 500;
var margin = {
top: 20,
right: 40,
bottom: 60,
left: 100
};
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
// Create an SVG wrapper, append an SVG group that will hold our chart and shift the latter by left and top margins
var svg = d3.select("#scatter")
.append("svg")
.attr("width", width)
.attr("height", height);
var chartGroup = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// Import Data
d3.csv("data.csv").then(function(censusData) {
// Parse Data & Cast as numbers
censusData.forEach(function(data) {
data.healthcare = +data.healthcare;
data.poverty = +data.poverty;
});
// Create scale functions
var xLinearScale = d3.scaleLinear()
.domain(d3.extent(censusData, d => d.poverty))
.range([0, width]);
var yLinearScale = d3.scaleLinear()
.domain([0, d3.max(censusData, d => d.healthcare)])
.range([height, 0]);
// Create axis functions
var bottomAxis = d3.axisBottom(xLinearScale);
var leftAxis = d3.axisLeft(yLinearScale);
// Append axes to the chart
chartGroup.append("g")
.attr("transform", `translate(0, ${height})`)
.call(bottomAxis);
chartGroup.append("g")
.call(leftAxis);
// Create circles
var circlesGroup = chartGroup.selectAll("Circle")
.data(censusData)
.enter()
.append("circle")
.attr("cx", d => xLinearScale(d.poverty))
.attr("cy", d => yLinearScale(d.healthcare))
.attr("r", "15")
.attr("fill", "blue")
.attr("opacity", "0.5");
// Create axes labels
chartGroup.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left + 40)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.attr("class", "axisText")
.text("Lacks Healthcare (%)");
chartGroup.append("text")
.attr("transform", `translate(${width / 2}, ${height + margin.top + 30})`)
.attr("class", "axisText")
.text("In Poverty (%)");
});
And here's the accompanying HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3Times</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/d3Style.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-12">
<h1>D3Times</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-9">
<div id="scatter">
<!-- We append our chart here. -->
</div>
</div>
</div>
</div>
<!-- Footer-->
<div id="footer">
<p>The Coding Boot CampĀ©2016</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.js"></script>
<script type="text/javascript" src="assets/js/app.js"></script>
</body>
</html>
When I run the code, here's the scatterplot I get:
Why isn't the X-axis displaying? Can anyone help with this?
Any help is greatly appreciated! Thanks in advance.
P.S: To run the code, I have to go into my project folder and run
python -m http.server
This hosts the page at localhost:8000 in the web browser.
You're using the famous margin convention to create your dataviz:
However, for this to work, you have to set the SVG size using the total width and height...
var svgWidth = 960;
var svgHeight = 500;
...not the ones computed after removing the margins:
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
Therefore, it should be:
var svg = d3.select("#scatter")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
Here is your updated code:
var csv = `id,state,healthcare,poverty
1,Alabama,13.9,19.3
2,Alaska,15,11.2,11.4
3,Arizona,14.4,18.2
4,Arkansas,16.3,18.9
5,California,14.8,16.4
6,Colorado,12.8,12
7,Connecticut,8.7,10.8
8,Delaware,8.7,12.5`;
const censusData = d3.csvParse(csv)
var svgWidth = 960;
var svgHeight = 500;
var margin = {
top: 20,
right: 40,
bottom: 60,
left: 100
};
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
// Create an SVG wrapper, append an SVG group that will hold our chart and shift the latter by left and top margins
var svg = d3.select("#scatter")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
var chartGroup = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// Parse Data & Cast as numbers
censusData.forEach(function(data) {
data.healthcare = +data.healthcare;
data.poverty = +data.poverty;
});
// Create scale functions
var xLinearScale = d3.scaleLinear()
.domain(d3.extent(censusData, d => d.poverty))
.range([0, width]);
var yLinearScale = d3.scaleLinear()
.domain([0, d3.max(censusData, d => d.healthcare)])
.range([height, 0]);
// Create axis functions
var bottomAxis = d3.axisBottom(xLinearScale);
var leftAxis = d3.axisLeft(yLinearScale);
// Append axes to the chart
chartGroup.append("g")
.attr("transform", `translate(0, ${height})`)
.call(bottomAxis);
chartGroup.append("g")
.call(leftAxis);
// Create circles
var circlesGroup = chartGroup.selectAll("Circle")
.data(censusData)
.enter()
.append("circle")
.attr("cx", d => xLinearScale(d.poverty))
.attr("cy", d => yLinearScale(d.healthcare))
.attr("r", "15")
.attr("fill", "blue")
.attr("opacity", "0.5");
// Create axes labels
chartGroup.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left + 40)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.attr("class", "axisText")
.text("Lacks Healthcare (%)");
chartGroup.append("text")
.attr("transform", `translate(${width / 2}, ${height + margin.top + 30})`)
.attr("class", "axisText")
.text("In Poverty (%)");
<head>
<meta charset="UTF-8">
<title>D3Times</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/d3Style.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-12">
<h1>D3Times</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-9">
<div id="scatter">
<!-- We append our chart here. -->
</div>
</div>
</div>
</div>
<!-- Footer-->
<div id="footer">
<p>The Coding Boot CampĀ©2016</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.js"></script>
<script type="text/javascript" src="assets/js/app.js"></script>
</body>

Hide and show svg element with transition

How can I hide and show an svg element using transition?
I try this code:
<div id="bubble"></div>
<div id="buttonHide"><button>Hide</button></div>
<div id="buttonShow"><button>Show</button></div>
d3.select("#bubble")
.append("svg")
.append("g")
.append("circle")
.attr("class", "bubble")
.attr("transform", "translate(100, 100)")
.attr("r", 50)
.attr("fill", "black");
d3.select("#buttonHide").on("click", function() {
d3.select(".bubble").transition().attr('visibility', 'hidden').duration(1000);
});
d3.select("#buttonShow").on("click", function() {
d3.select(".bubble").transition().attr('visibility', 'visible').duration(1000);
});
d3.select("#bubble")
.append("svg")
.append("g")
.append("circle")
.attr("class", "bubble")
.attr("transform", "translate(100, 100)")
.attr("r", 50)
.attr("fill", "black");
d3.select("#buttonHide").on("click", function() {
d3.select(".bubble").transition().duration(1000).attr('visibility', 'hidden');
});
d3.select("#buttonShow").on("click", function() {
d3.select(".bubble").transition().duration(1000).attr('visibility', 'visible');
});
<html lang='en'>
<head>
<meta charset='utf-8'>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
</head>
<body>
<div id="bubble"></div>
<div id="buttonHide"><button>Hide</button></div>
<div id="buttonShow"><button>Show</button></div>
</body>
</html>
But transition doesn't work.
You could play with the opacity style instead of switching the visibility attribute:
d3.select("#bubble")
.append("svg")
.append("g")
.append("circle")
.attr("class", "bubble")
.attr("transform", "translate(100, 100)")
.attr("r", 50)
.attr("fill", "black")
.style("opacity", 1);
d3.select("#buttonHide").on("click", function() {
d3.select(".bubble").transition().duration(1000).style("opacity", 0);
});
d3.select("#buttonShow").on("click", function() {
d3.select(".bubble").transition().duration(1000).style("opacity", 1);
});
<html lang='en'>
<head>
<meta charset='utf-8'>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
</head>
<body>
<div id="bubble"></div>
<div id="buttonHide"><button>Hide</button></div>
<div id="buttonShow"><button>Show</button></div>
</body>
</html>
This way, the transition will be applied on the opacity, which will transition from 0 to 1 (unhide) or from 1 to 0 (hide).
To set the opacity:
d3.select(".bubble").transition().duration(1000).style("opacity", 1);
The transition is in fact expecting a change which can be interpolated between two values. This is the case for the opacity (all the way between 0 and 1), whereas the visibility attribute is a simple switch (on/off).

I don't know how to change a color in a d3.js US map when hovered over

I have this map of the USA. I know how to bind other data, change colors of states but the only thing I don't know how to change the default orangish color when a state is hovered over.
You can find it here as well: http://blockbuilder.org/malcolm-decuire/34d2ce39d3b8c2f8a577
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://datamaps.github.io/scripts/datamaps.all.min.js?v=1"></script>
<h2> American Lynches | 1830-1970</h2>
<div id="map" style="position: relative; width: 900px; max-height: 900px;"></div>
<script>
var map = new Datamap({
scope: 'usa',
element: document.getElementById('map'),
geographyConfig:{
highlightBorderColor: '#bada55',
popupTemplate: function(geography, data){
return '<div class="hoverinfo">' + geography.properties.name + ' White/Black ' + data.LynchWhite + ' / ' + data.LynchBlack
},
},
height: 500,
fills: {
'none': '#999999',
'White': '#CC4731',
'Black': '#306596',
},
data: {
"AZ": {
"fillKey": "White",
"LynchWhite": 31,
"LynchBlack": 0
},
...
}
})
//keep this code
map.bubbles([ ], {
popupTemplate: function(geography, data) {
return "<div class='hoverinfo'>It is " + data.name + "</div>";
}
});
</script>
<script>
var ordinal = d3.scale.ordinal()
.domain(["white", "black", "none"])
.range([ "rgb(204,71,49)", "rgb(48,101,150)", "rgb(153,153,153"]);
var svg = d3.select("svg");
svg.append("g")
.attr("class", "legendOrdinal")
.attr("transform", "translate(450,450)");
var legendOrdinal = d3.legend.color()
.shape("path", d3.svg.symbol().type("triangle-up").size(150)())
.shapePadding(10)
.scale(ordinal);
svg.select(".legendOrdinal")
.call(legendOrdinal);
</script>
</body>
According to the documentation, it's controlled by the highlightFillColor config option:
geographyConfig:{
highlightFillColor: '#FC8D59'
}

d3.js d3.json is not working - how to make this function work?

Trying to develop a data visualization app with d3.js
Using a local json file named "yelp_test_set_business.json"
When I attempt to use d3.json to load this data, nothing is being passed to the callback function, which, in tern, also triggers an error within crossfilter.js library.
here is my entire file:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<script src='javascript/d3.js' type='text/javascript'></script>
<script src='javascript/crossfilter.js' type='text/javascript'></script>
<script src='javascript/dc.js' type='text/javascript'></script>
<script src='javascript/jquery-1.12.1.min.js' type='text/javascript'></script>
<script type='text/javascript'>
/********************************************************
* *
* dj.js example using Yelp Kaggle Test Dataset *
* Eol 9th May 2013 *
* *
********************************************************/
/********************************************************
* *
* Step0: Load data from json file *
* *
********************************************************/
d3.json("data/yelp_test_set_business.json", function (yelp_data) {
/********************************************************
* *
* Step1: Create the dc.js chart objects & ling to div *
* *
********************************************************/
var bubbleChart = dc.bubbleChart("#dc-bubble-graph");
var pieChart = dc.pieChart("#dc-pie-graph");
var volumeChart = dc.barChart("#dc-volume-chart");
var lineChart = dc.lineChart("#dc-line-chart");
var dataTable = dc.dataTable("#dc-table-graph");
var rowChart = dc.rowChart("#dc-row-graph");
/********************************************************
* *
* Step2: Run data through crossfilter *
* *
********************************************************/
var ndx = crossfilter(yelp_data);
/********************************************************
* *
* Step3: Create Dimension that we'll need *
* *
********************************************************/
// for volumechart
var cityDimension = ndx.dimension(function (d) { return d.city; });
var cityGroup = cityDimension.group();
var cityDimensionGroup = cityDimension.group().reduce(
//add
function(p,v){
++p.count;
p.review_sum += v.review_count;
p.star_sum += v.stars;
p.review_avg = p.review_sum / p.count;
p.star_avg = p.star_sum / p.count;
return p;
},
//remove
function(p,v){
--p.count;
p.review_sum -= v.review_count;
p.star_sum -= v.stars;
p.review_avg = p.review_sum / p.count;
p.star_avg = p.star_sum / p.count;
return p;
},
//init
function(p,v){
return {count:0, review_sum: 0, star_sum: 0, review_avg: 0, star_avg: 0};
}
);
// for pieChart
var startValue = ndx.dimension(function (d) {
return d.stars*1.0;
});
var startValueGroup = startValue.group();
// For datatable
var businessDimension = ndx.dimension(function (d) { return d.business_id; });
/********************************************************
* *
* Step4: Create the Visualisations *
* *
********************************************************/
bubbleChart.width(650)
.height(300)
.dimension(cityDimension)
.group(cityDimensionGroup)
.transitionDuration(1500)
.colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"])
.colorDomain([-12000, 12000])
.x(d3.scale.linear().domain([0, 5.5]))
.y(d3.scale.linear().domain([0, 5.5]))
.r(d3.scale.linear().domain([0, 2500]))
.keyAccessor(function (p) {
return p.value.star_avg;
})
.valueAccessor(function (p) {
return p.value.review_avg;
})
.radiusValueAccessor(function (p) {
return p.value.count;
})
.transitionDuration(1500)
.elasticY(true)
.yAxisPadding(1)
.xAxisPadding(1)
.label(function (p) {
return p.key;
})
.renderLabel(true)
.renderlet(function (chart) {
rowChart.filter(chart.filter());
})
.on("postRedraw", function (chart) {
dc.events.trigger(function () {
rowChart.filter(chart.filter());
});
});
;
pieChart.width(200)
.height(200)
.transitionDuration(1500)
.dimension(startValue)
.group(startValueGroup)
.radius(90)
.minAngleForLabel(0)
.label(function(d) { return d.data.key; })
.on("filtered", function (chart) {
dc.events.trigger(function () {
if(chart.filter()) {
console.log(chart.filter());
volumeChart.filter([chart.filter()-.25,chart.filter()-(-0.25)]);
}
else volumeChart.filterAll();
});
});
volumeChart.width(230)
.height(200)
.dimension(startValue)
.group(startValueGroup)
.transitionDuration(1500)
.centerBar(true)
.gap(17)
.x(d3.scale.linear().domain([0.5, 5.5]))
.elasticY(true)
.on("filtered", function (chart) {
dc.events.trigger(function () {
if(chart.filter()) {
console.log(chart.filter());
lineChart.filter(chart.filter());
}
else
{lineChart.filterAll()}
});
})
.xAxis().tickFormat(function(v) {return v;});
console.log(startValueGroup.top(1)[0].value);
lineChart.width(230)
.height(200)
.dimension(startValue)
.group(startValueGroup)
.x(d3.scale.linear().domain([0.5, 5.5]))
.valueAccessor(function(d) {
return d.value;
})
.renderHorizontalGridLines(true)
.elasticY(true)
.xAxis().tickFormat(function(v) {return v;}); ;
rowChart.width(340)
.height(850)
.dimension(cityDimension)
.group(cityGroup)
.renderLabel(true)
.colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"])
.colorDomain([0, 0])
.renderlet(function (chart) {
bubbleChart.filter(chart.filter());
})
.on("filtered", function (chart) {
dc.events.trigger(function () {
bubbleChart.filter(chart.filter());
});
});
dataTable.width(800).height(800)
.dimension(businessDimension)
.group(function(d) { return "List of all Selected Businesses"
})
.size(100)
.columns([
function(d) { return d.name; },
function(d) { return d.city; },
function(d) { return d.stars; },
function(d) { return d.review_count; },
function(d) { return 'Map"}
])
.sortBy(function(d){ return d.stars; })
// (optional) sort order, :default ascending
.order(d3.ascending);
/********************************************************
* *
* Step6: Render the Charts *
* *
********************************************************/
dc.renderAll();
});
</script>
<link href='stylesheets/bootstrap.min.css' rel='stylesheet' type='text/css'>
<!--<link href='stylesheets/dc.css' rel='stylesheet' type='text/css'>-->
<!--<script src='simple_vis.js' type='text/javascript'></script>-->
</head>
<body>
<div class='container' id='main-container'>
<div class='content'>
<div class='container' style='font: 10px sans-serif;'>
<h3>Visualisation of Kaggle Yelp Test Business Data set (using dc.js)</h3>
<h4>Demo for the Dublin Data Visualisation Meetup Group</h4>
<div class='row-fluid'>
<div class='remaining-graphs span8'>
<div class='row-fluid'>
<div class='bubble-graph span12' id='dc-bubble-graph'>
<h4>Average Rating (x-axis), Average Number of Reviews (y-axis), Number of Business' (Size)</h4>
</div>
</div>
<div class='row-fluid'>
<div class='pie-graph span4' id='dc-pie-graph'>
<h4>Average Rating in Stars (Pie)</h4>
</div>
<div class='pie-graph span4' id='dc-volume-chart'>
<h4>Average Rating in Stars / Number of Reviews (Bar)</h4>
</div>
<div class='pie-graph span4' id='dc-line-chart'>
<h4>Average Rating in Stars / Number of Reviews (Line)</h4>
</div>
</div>
<!-- /other little graphs go here -->
<div class='row-fluid'>
<div class='span12 table-graph'>
<h4>Data Table for Filtered Businesses</h4>
<table class='table table-hover dc-data-table' id='dc-table-graph'>
<thead>
<tr class='header'>
<th>Name</th>
<th>City</th>
<th>Review Score (in Stars)</th>
<th>Total Reviews</th>
<th>Location</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div class='remaining-graphs span4'>
<div class='row-fluid'>
<div class='row-graph span12' id='dc-row-graph' style='color:black;'>
<h4>Reviews Per City</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
The following call:
d3.json("data/yelp_test_set_business.json", function (yelp_data) { ...}
returns nothing in yelp_data
Does anyone know why this is hapenning?
Instead of doing like this to load your JSON:
d3.json("data/yelp_test_set_business.json", function (yelp_data) {
It should have been:
d3.json("data/yelp_test_set_business.json", function (error, yelp_data) {
Read this
Most of the time, this error is related to the fact that you just open the html file in your browser, which then tries to open the json file using the file:/// protocol, resulting in a cross origin violation.
D3 doc on requests.
One way to fix it is just by using a web server to serve the .html and the .json.
If you have python installed, just go to the folder where you file is located and run python -m SimpleHTTPServer, then navigate with your browser to http://localhost:8080. This way both the .html and .json will be served from the same origin (namely localhost:8080), and you will be able to load file via d3.json, d3.csv, etc...

How to align two svg's side by side in d3.js

I have two graphs(rectangles with text the other circles with text) to be displayed but instead of displaying one below the other,I want to display side by side i.e 2 charts displaying horizontally(one at the left of div and the other at right of div). I created 2 svg's and added the charts in to that. However when ever i change the top or bottom margin it is not working.
My code goes like:
<!DOCTYPE html>
<html xmlns:xlink="http://www.w3.org/1999/xlink">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Circle legends</title>
<script type="text/javascript" src="../../js/d3/d3.v3.js"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?1.27.2"></script>
<link rel="stylesheet" href="../../css/style.css" />
<style type="text/css">
</style>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
var width=960,height=500;
var margin = {top: 29.5, right: 29.5, bottom: 29.5, left: 59.5};
radiusScale = d3.scale.sqrt().domain([1, 100]).range([10, 39]),
colorScale = d3.scale.category10();
//Create the SVG for legends.
var svglegend = d3.select("#chart").append("svg").attr("id","svglegend")
.attr("width", width-100)
.attr("height", height -100)
.append("g")
.attr("transform", "translate(" + margin.left + "," + (margin.top +30) + ")");
//alert("Non-empty");
d3.json("SbuLegendData.json", function(data) {
jsondata = data;
rectangle= svglegend.selectAll("rect").data(data).enter().append("rect");
var RectangleAttrb = rectangle.attr("x", function (d) { return d.x_axis; })
.attr("y", function (d) { return d.y_axis; })
.attr("width",function(d) { return d.width; } )
.attr("height",function(d) { return d.height; })
.style("fill", function(d) { return d.color; });
var textparam = svglegend.selectAll("text").data(data).enter().append("text");
var text = textparam .attr("x", function (d) { return d.x_axis + d.width +10; })
.attr("y", function (d) { return d.y_axis + d.height-5; })
.attr("width",30 )
.attr("height",20)
.text(function(d) { return d.text; });
});
// Create the SVG container and set the origin.
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 + ")");
var i =0;
while (i<=50)
{
console.log("i value is " + i + " value of scale " +i+ " is " + radiusScale(i));
var g = svg.append("g");
g.append("circle")
.attr("id","circle" + i)
.attr("cx", i*12 )
.attr("cy", 30)
.attr("fill",colorScale(i))
.attr("r", radiusScale(i));
g.append("text").attr("dx",i*12).text(Math.round(radiusScale(i)));
i=i+10;
}
</script>
</body>
</html>
the json data contains:
[
{ "x_axis":40, "y_axis": 10,"width":50,"height":20,"color" : "#1f77b4","text":"F&R"},
{ "x_axis":40, "y_axis": 30,"width":50,"height":20,"color" : "#ff7f0e","text":"Legal"},
{ "x_axis":40, "y_axis": 50,"width":50,"height":20,"color" : "#2ca02c","text":"GGO"},
{ "x_axis":40, "y_axis": 70,"width":50,"height":20,"color" : "#d62728","text":"IP&S"},
{ "x_axis":40, "y_axis": 90,"width":50,"height":20,"color" : "#9467bd","text":"CORP"},
{ "x_axis":40, "y_axis": 110,"width":50,"height":20,"color": "#8c564b","text":"TAX"},
{ "x_axis":40, "y_axis": 130,"width":50,"height":20,"color" : "#e377c2","text":"REUTERS ALL"}
]
You need to use CSS for this. It's easier if you have two containers:
CSS:
.container {
float: left;
}
HTML:
<div class="container" id="chart1">
</div>
<div class="container" id="chart2">
</div>
Then use #chart1 and #chart2 in your code.

Resources