Hi everyone I am starting with D3.JS, and I want to show a bar with the temperature of a place.
This is my code
json_url= "https://data.cityofchicago.org/resource/7edu-s3u7.json";
var all_name_station = ["63rd Street Weather Station", "Foster Weather Station", "Oak Street Weather Station"];
var one_name_station = ["63rd Street Weather Station"];
var width = 900;
var height = 400;
$(document).ready(function(){
d3.json(json_url, function(data) {
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
one_name_station.forEach(function(station_item){
data.forEach(function(item_data){
if (item_data["station_name"] == station_item){
//console.log(item_data);
canvas.selectAll("rect")
.data(item_data)
.enter()
.append("rect")
.attr("width", function(d) {return d.air_temperature;})
.attr("height", 50)
.attr("y", function(d,i){return d;})
.attr("fill", "blue");
}
});
});
});
});
I take my data from JSON, there are many station but I start only represente the data for "63rd Street Weather Station"
But my problems is that this code don't return nothing. You can try here
What I missing!
Thanks in advance
Your immediate problem is that right now you are not passing an iterable to data, just an object. If you wrap item_data in an array it will create a single blue rectangle:
.data([item_data])
Then you will have other problems, however, such as setting y. I would recommend reformatting your data first into a list of objects (instead of appending them one at a time), and building off of one of the canonical bar chart examples.
I would pass array of data, not by one item. So, compile the array of proper stations first, and then pass it to d3:
//array of objects
var stations = [{name: "Station 1", air_temperature: 19.5},
{name: "Station 2", air_temperature: 21.5},
{name: "Station 3", air_temperature: 20},];
//adding bars
var bars = canvas.selectAll("rect")
.data(stations)
.enter()
.append("rect")
.attr("width", function(d) {return d}) //guess: pass through function figuring out the right scale
.attr("height", 50) //guess: pass through function figuring out the right scale
.attr("y", function(d,i){return d.air_temperature;}) //guess: multiply by scaleFactor, obtained depending on number of entries in data and canvas size
.attr("fill", "blue"); //guess: pass through d3.scale.linear() function
Related
I'm learning D3 and have JSON data. I want to build multiple bars from this JSON data to draw graph like this already built in excel. I can draw one line of Pax_Rev on SVG but I'm not sure how to add other lines from the data. When I do console.log(dataset.length), it shows me 0 which means only one item in dataset which is expected.
<script>
var dataset = [{"Pax_Rev": 1000, "Crg_Rev": 500,
"Fixed_Costs": 800, "Variable_Costs": 200}];
var width = 500;
var height = 1000;
var barPadding = 1;
var svg = d3.select("body")
.append("svg")
.append("g")
.attr("width", width)
.attr("height", height)
.attr("class", "svg")
svg3.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", function(d){
return height - d.Pax_Rev // How to add other items like Crg_Rev etc?
})
.attr("width", 20)
.attr("height", function(d){
return d.Pax_Rev
});
</script>
As I explained in your previous question, this is the expected behaviour. Since you have just one object in your data array, D3 "enter" selection will create just one element.
If you look at the API, you'll see that selection.data():
Joins the specified array of data with the selected elements[...] The specified data is an array of arbitrary values (e.g., numbers or objects). (emphases mine)
Therefore, we have to convert that huge object in several objects. This is one of several possible approaches:
var dataset = [{
"Pax_Rev": 1000,
"Crg_Rev": 500,
"Fixed_Costs": 800,
"Variable_Costs": 200
}];
var data = [];
for (var key in dataset[0]) {
data.push({
category: key,
value: dataset[0][key]
})
}
console.log(data)
Now, we have a data array, with several objects, one for each bar, and we can create our bar chart.
Here is a demo:
var dataset = [{
"Pax_Rev": 1000,
"Crg_Rev": 500,
"Fixed_Costs": 800,
"Variable_Costs": 200
}];
var data = [];
for (var key in dataset[0]) {
data.push({
category: key,
value: dataset[0][key]
})
}
var svg = d3.select("svg");
var yScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.value
})])
.range([120, 10]);
var xScale = d3.scaleBand()
.domain(data.map(function(d) {
return d.category
}))
.range([40, 280])
.padding(0.2);
var rects = svg.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr("fill", "steelblue")
.attr("x", function(d) {
return xScale(d.category)
})
.attr("width", xScale.bandwidth())
.attr("y", function(d) {
return yScale(d.value)
})
.attr("height", function(d) {
return 120 - yScale(d.value)
});
var yAxis = d3.axisLeft(yScale);
var xAxis = d3.axisBottom(xScale);
svg.append("g").attr("transform", "translate(40,0)").call(yAxis);
svg.append("g").attr("transform", "translate(0,120)").call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Let me preface this by saying I am brand new to D3.js and coding in general. I am an infographic artist and I've been using QGIS to generate maps, but am trying to use D3.js to generate a choropleth map for a story about Opioid deaths. Basically I am trying to recreate this map.
map from the Economist
I have tried to start by using this map by Mike Bostock and changing some of the parameters but am getting stuck with the color range and scale. The measurement is 1 per 100,000 population. I have a domain that starts at 1.543385761 and ends at 131.0814217.
The code I'm struggling with is around the scale input and output:
var x = d3.scaleLinear()
.domain([0, 132])
.rangeRound([600, 860]);
var color = d3.scaleThreshold()
.domain(d3.range(2, 10))
.range(d3.schemeBlues[9]);
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(0, 40)");
g.selectAll("rect")
.data(color.range().map(function(d) {
d = color.invertExtent(d);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().append("rect")
.attr("height", 8)
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.attr("fill", function(d) { return color(d[0]); });
I can see that I need some bit of code that will define everything 25 and over as the darkest color. Not even sure I want that to be my final legend but I'd love to know how to reproduce that. I am shocked I was able to get this far but feel a bit lost right now. thank you in advance!
Let's examine your scale:
var color = d3.scaleThreshold()
.domain(d3.range(2, 10))
.range(d3.schemeBlues[9]);
Your domain is an array of created like so:
d3.range(2,10) // [2,3,4,5,6,7,8,9]
These are your thresholds, colors will be mapped based on values that are less than or equal to 2, more than two up to three, more than three and up to four .... and over 9. This domain is mapped to nine values defined in the range:
d3.schemeBlues[9] // ["#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", #6baed6", #4292c6", "#2171b5", "#08519c", "#08306b"]
To set the thresholds for those colors so that values over 25 are one color, define the domain with array that has the appropriate threshold(s):
.domain([2,3,4,5,6,7,8,25]);
In the snippet below, this domain is applied. Rectangles have colors dependent on their location, all rectangles after the 25th (count left to right then line by line) one will be of one color.
var color = d3.scaleThreshold()
.domain([2,3,4,5,6,7,8,25])
.range(d3.schemeBlues[9]);
var svg = d3.select("body")
.append("svg")
.attr("width",500)
.attr("height",500);
var rects = svg.selectAll("rect")
.data(d3.range(100))
.enter()
.append("rect")
.attr("width",15)
.attr("height", 15)
.attr("y", function(d,i) { return Math.floor(i / 10) * 20 + 10 })
.attr("x", function(d,i) { return i % 10 * 20 })
.attr("fill", function(d) { return color(d); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
I'm new to D3 and am trying to build a table like structure out of rectangles. I would like the header to be a different color than the rest of the rectangles. I've written the following code:
table = svgContainer.selectAll('rect')
.data([managedObj])
.enter()
.append('rect')
.attr("width", 120)
.attr("height", 20)
.attr("fill", "blue")
.text(function(d) {
return d.name;
});
// create table body
table.selectAll('rect')
.data(managedObj.data)
.enter()
.append('rect')
.attr("y", function() {
shift += 20;
return shift;
})
.attr("width", 120)
.attr("height", 20)
.attr("fill", "red")
.text(function(d) {
return d.name;
});
This is producing the following results:
This is almost what I intended except it is nesting the second group of rectangles inside the first rectangle. This causes only the first blue rectangle to be visible. I'm assuming this has something to do with calling the data method twice. How can I fix this issue?
I think I understand the intended result, so I'll give it a go:
This line :
table.selectAll('rect')
is selecting the rectangle just created here:
table = svgContainer.selectAll('rect')....append('rect')....
You don't want to append rectangles to that rectangle (or any rectangle for that matter) because this won't work, but you do want to append them to the SVG itself.
So instead of table.selectAll you should be using svgContainer.selectAll, but there are two other issues:
if you use svgContainer.selectAll('rect') you will be selecting the rect you have already appended, when you actually want an empty selection. See the answer here.
you cannot place text in a rect (See answer here), instead you could append g elements and then append text and rect elements to those. And, for ease of positioning, you could translate the g elements so that positioning the rectangles and text is more straight forward.
So, your code could look like:
var data = ["test1","test2","test3","test4"];
var svgContainer = d3.select('body').append('svg').attr('width',900).attr('height',400);
var header = svgContainer.selectAll('g')
.data([data])
.enter()
.append('g')
.attr('transform','translate(0,0)');
header.append('rect')
.attr("width", 120)
.attr("height", 20)
.attr("fill", "blue");
header.append('text')
.attr('y',15)
.attr('x',5)
.text(function(d) {
return "header";
});
// create table body
var boxes = svgContainer.selectAll('.box')
.data(data)
.enter()
.append('g')
.attr('class','box')
.attr('transform',function(d,i) { return 'translate(0,'+((i+1)*20)+')'; });
boxes.append('rect').attr("width", 120)
.attr("height", 20)
.attr("fill", "red");
boxes.append('text')
.attr('y',15)
.attr('x',5)
.text(function(d) {
return d;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I'm playing around with the "update" pattern in D3.js. I am just creating a simple bar graph that will update the data when you press the "Change" button.
My problem is that when you press the "Change" button, the first three rendered bars do not get re-rendered. I debugged and saw that the data was properly applied (__data__ was correct) but the re-application failed.
Here is my code and a link to it in CodePen:
var myData = [ 100, 200, 300 ];
d3.select('body').append('button').text("Change").on("click", function() {
myData = [200, 400, 600, 700, 800, 900, 1000];
update(myData);
});
var svg = d3.select('body').append('svg')
.attr("class", "chart")
.attr("y", 30);
var update = function(data) {
var bars = svg.selectAll('g')
.data(data);
var groups = bars.enter()
.append("g")
.attr("transform", function(d,i) {return "translate(0," + i*25 + ")"});
groups
.append("rect")
.attr("height", 25)
.attr("fill", "pink")
.attr("stroke", "white");
groups
.append("text")
.attr("x", 10)
.attr("y", 18)
.attr("fill", "red");
bars.selectAll("rect")
.attr("width", String);
bars.selectAll("text")
.text(String);
};
update(myData);
It works if you change the .selectAll() in your update selection handling to .select():
bars.select("rect")
.attr("width", String);
bars.select("text")
.text(String);
By using selectAll(), you're accessing the data that is bound to the elements that you're selecting (i.e. the rectangles and text elements), which was bound when you appended the elements. This data hasn't been updated though as you've only updated it for the containing g elements. Using .select() instead also binds the new data to the child elements.
The general pattern that you're using is a nested selection and can be a bit confusing to start with and lead to unexpected results.
I'm attempting to make a Paired Bar Graph between glob and local within my JS Object/Array. I've made bar graphs in D3 previously, but haven't used objects. I'm finding it difficult to access the correct data.
Eventually, the keyword data will be used in the axis. And the cpc will be used as a tooltip.
Here's the code that I have so far: (or see my JSFiddle)
var w = 600;
var h = 400;
var colors = ["#377EB8", "#4DAF4A"];
var dataset = {"keyword": ["payday loans", "title loans", "personal loans"],
"glob": ["1500000", "165000", "550000"],
"local": ["673000", "165000", "301000"],
"cpc": ["14.11", "12.53", "6.14"]
};
var series = 2; // Global & Local
var x0Scale = d3.scale.ordinal()
.domain(d3.range(dataset.glob.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {return d.glob;})])
.range([0, h]);
var glob = function(d) {
return d.glob;
};
//SVG element
var svg = d3.select("#searchVolume")
.append("svg")
.attr("width", w)
.attr("height", h);
// Graph Bars
svg.selectAll("rect")
.data(dataset, glob) //access the series here?
.enter()
.append("rect")
.attr("x", function(d, i){
return x0Scale(i);
})
.attr("y", function(d) {
return h - yScale(d.glob);
})
.attr("width", x0Scale.rangeBand())
.attr("height", function(d) {
return yScale(d.glob); // ***************
})
.attr("fill", colors[1]);
Currently, the chart doesn't get populated. I assume I am not accessing values correctly. I'm simply trying to get data from glob to make sure I'm accessing things correctly - and then from there I was going to populate both series, etc. Is my issue not accessing key/values correctly?
Take a look at this: http://jsfiddle.net/juY5E/2/
I was able to get three bars by changing .data(dataset, glob) to .data(dataset.glob) and then changing d.glob to +d for the 'y' attr, the 'height' attr and in yScale.domain
to be able to switch between glob and local, you may want to restructure the data.