I have 14 series of lines. I would like to show them with a spacing between them. something like in the image, I think the best option is with the translate property. I do not know how to do it with each line. I'm trying to get my data between 0 and 100
http://plnkr.co/edit/qmkxYEJYpIkXUQUMQMDa?p=preview
paths.attr('transform', null)
.transition()
.duration(duration)
.ease('linear')
.attr('transform', 'translate(' + x(now - (limit - 1) * duration) + ')')
.each('end', tick)
Use a scale band (or v3 ordinal scale with rangeBand) to translate the lines, and the scale linear to draw the lines
http://plnkr.co/edit/qs1i4sVzBXl6de7b8HJ3?p=preview
var band = d3.scale.ordinal()
.domain(ids)
.rangeBands([height, 0])
and
for (var name in groups) {
var group = groups[name];
let g = paths.append("g")
.attr("transform", function(d,i){
return "translate(0, " + band(name) +")";
});
group.path = g.append('path')
.data([group.data])
.attr('class', name + ' group')
.style('stroke', group.color)
}
Your problem right now is that horrendous for...in loop. Do not use loops to append elements in a D3 code. It's not only unnecessary but it will also make things very difficult to change, like your situation right now.
Thus, since you have that loop (I'll not refactor the code to eliminate that, it's simply too much work for a — free — S.O. answer), this is my solution:
First, increase the height of the chart and decrease the range of the y scale. Here, I'm setting the height to 800 and the range to [45, 0]. Change that accordingly (or, if you want to avoid magic numbers — always a good idea — have a look at the other answer)
Then, in the for loop, translate each element according to a counter, here named index:
var index = 0;
for (var name in groups) {
var group = groups[name]
group.path = paths.append('path')
.data([group.data])
.attr('class', name + ' group')
.style('stroke', group.color)
.attr("transform", function() {
return "translate(0," + (55 * index++) + ")";
})
}
This is your plunker with those changes: http://plnkr.co/edit/NPhWMpcorXhAubwytmOe?p=preview
Related
I'm trying to position labels on map overlapping-free by using using d3fc-label-label.js in combination with d3.js. While labeling the map by basic d3 functions works well, the approach with the help of d3fc-label-label.js (heavily inspired by this example) produces a map with all the labels placed in top left corner.
Here's the javascript part that does the job
var width = 1300,
height = 960;
var projection = d3.geoMercator()
.scale(500)
// Center the Map to middle of shown area
.center([10.0, 50.5])
.translate([width / 2, height / 2]);
// ??
var path = d3.geoPath()
.projection(projection)
.pointRadius(2);
// Set svg width & height
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// var g = svg.append("g");
d3.json("europe_wgs84.geojson", function(error, map_data) {
if (error) return console.error(error);
// var places = topojson.feature(map_data, map_data.objects.places);
// "path" instead of ".subunit"
svg.selectAll("path")
.data(map_data.features)
.enter().append("path")
.attr("d", path)
.attr("class", function(d) { return "label " + d.id})
var labelPadding = 2;
// the component used to render each label
var textLabel = fc.layoutTextLabel()
.padding(labelPadding)
//.value(function(d) { return map_data.properties.iso; });
.value(function(d) { return d.properties.iso; });
// use simulate annealing to find minimum overlapping text label positions
var strategy = fc.layoutGreedy();
// create the layout that positions the labels
var labels = fc.layoutLabel(strategy)
.size(function(_, i, g) {
// measure the label and add the required padding
var textSize = d3.select(g[i])
.select('text')
.node()
.getBBox();
return [textSize.width + labelPadding * 2, textSize.height + labelPadding * 2];
})
.position(function(d) { return projection(d.geometry.coordinates); })
.component(textLabel);
// render!
svg.datum(map_data.features)
.call(labels);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.0/d3.min.js"></script>
See the gist that includes the data and a HTML file.
I would guess the issue is related to append the labels correctly to path of the map. Sadly, I haven't figured it out and would greatly appreciate any help!
I believe the problem lies in the fact that you are not passing single coordinates as the label's position.
layoutLabel.position(accessor)
Specifies the position for each item in the associated array. The
accessor function is invoked exactly once per datum, and should return
the position as an array of two values, [x, y].
In the example you show, that you are basing the design on, the variable places contains point geometries, it is to these points that labels are appended. Looking in the topojson we find places looking like:
"places":{"type":"GeometryCollection","geometries":[{"type":"Point","coordinates":[5868,5064],"properties":{"name":"Ayr"}},{"type":"Point","coordinates":[7508,6637],"properties":{"name":"Aberdeen"}},{"type":"Point","coordinates":[6609,5933],"properties":{"name":"Perth"}},...
Note that geometries.coordinates of each point contains one coordinate. However, in your code, d.geometry.coordinates contains an array of coordinates as it contains the boundary points of the entire path of each feature. This will cause errors in label placement. Instead, you might want to use path.centroid(d), this will return a single coordinate that is at the center of each country/region/path. Placement might not be perfect, as an extreme example, a series of countries arranged as concentric rings will have the same centroid. Here is a basic block showing placement using path.centroid (this shows only the placement - not the formatting of the labels as I'm not familiar with this library extension).
If you were wondering why the linked example's regional labels appear nicely, in the example each region has a label appended at its centroid, bypassing d3fc-label-layout altogether:
svg.selectAll(".subunit-label")
.data(subunits.features)
.enter().append("text")
.attr("class", function(d) { return "subunit-label " + d.id; })
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.properties.name; });
I'm trying to create an area chart for statistics on each US state. I have a single number statistic for each state; an element of my data list looks like the following:
{'state':'CA','count':4000}
Currently, my area chart looks like this. The task is mainly complete, but you may notice how the very last category (in this case, UTAH) isn't filled. I'm not quite sure how to get around this. close_up
I am using a scaleBand axis; this felt appropriate. Perhaps it is not the correct approach. Here is the JS behind the chart:
var svg_area = d3.select("#area")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom),
g_area = svg_area.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand().range([0, width]),
y = d3.scaleLinear().range([height, 0]);
var area = d3.area()
.x(function(d) { return x(d.state); })
.y0(height)
.y1(function(d) { return y(d.count); });
d3.csv('data/states.csv', function(data) {
data.forEach(function(d) {
d.count = +d.count;
});
data.sort(function(a, b){
return b.count-a.count;
});
data = data.slice(0,30);
x.domain(data.map(function(d) { return d.state; }));
y.domain([0, d3.max(data, function(d) { return d.count; })]);
g_area.append('path')
.datum(data)
.attr('fill', solar[1])
.attr("class", "area")
.attr('d', area);
g_area.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g_area.append("g")
.attr("class", "y-axis")
.attr("transform", "translate(0," + 0 + ")")
.call(d3.axisLeft(y));
});
Any suggestions on how I can fix this? Thanks for any feedback!
Contrary to your question's title (now edited), the area chart is not "leaving out the last data point".
What you're seeing is the expected result, since you are using a band scale. Actually, that value just above the horizontal axis (just in the "edge" of the area chart) is Utah value! Try to understanding it with this explanation: Imagine a bar chart with your data. Each bar has, of course, a given width. Now, draw a path going from the top left corner of one bar to the top left corner of the next bar, starting at the first bar and, when reaching the last bar, going down from the top left corner to the axis. That's the area you have right now.
There are two solutions here. The first one is using a point scale instead:
var x = d3.scalePoint().range([0, width])
However, this will trim the "margins" of the area path, before the first state and after the last state (Utah). That means, the area chart will start right over California tick and end right over Utah tick.
If you don't want that there is a second solution, which is hacky, but will keep those "margins": add the bandwidth() to the last state in the area generator:
var area = d3.area()
.x(function(d, i) {
return i === data.length - 1 ?
x(d.state) + x.bandwidth() : x(d.state)
})
It may be worth noting that, using a band scale, your chart is technically incorrect: the values in the area for each state are not over the tick for that state.
Because I am having an issue with my own code, I am studying below link:
https://bost.ocks.org/mike/path/
I think I get below
// push a new data point onto the back
data.push(random());
// redraw the line, and then slide it to the left
path
.attr("d", line)
.attr("transform", null)
.transition()
.attr("transform", "translate(" + x(-1) + ")");
// pop the old data point off the front
data.shift();
But the part that doesn't work for me and I don't understand is
.attr("transform", "translate(" + x(-1) + ")");
My code's x is like below:
var x = d3.time.scale().range([-5, width])
domain is not known at this time and later domain is defined as
x.domain(d3.extent(callbackData, function(d){return d.reg_date;}));
I try to use x(-1) but entire graph(except axis) disappears when I call for update so I use something like below and initially, it seems to work.(graph shifts to the left). But as more data comes in(btw, my data comes in and updates the data properly(shift off the front data and push latest into the back) graph starts to shifting towards the right. I can see graph start taking points from the front(which is correct) but problem is, graph is starting to shift to right(instead of left).
Really beating my head w/ this issue so hopefully someone can kindly advise.
path
.attr("d",line)
.attr('transform', null)
.transition()
.duration(300)
.ease('linear')
.attr("transform", "translate(" + -2 + ")");
This is a quick implementation : https://jsfiddle.net/thatOneGuy/j2eovk9k/8/
I have added this to work out distance between the x ticks :
var testtickArr = y.ticks(10);
var testtickDistance = y(testtickArr[testtickArr.length - 2]) - y(testtickArr[testtickArr.length - 1]);
Then used this as the distance to move the path :
path
.attr("d", line)
.transition()
.duration(1000)
.ease('linear')
.attr("transform", function(d) {
console.log(d)
return "translate(" + (pathTrans) + ")";
})
Also, update the translation value :
pathTrans -= testtickDistance;
The way you're updating your data can be improved. But this should help you with the transition. This is still not working ok at all as the distances between your points are not equal. For yours to work like the example you need equal distances between each points so it transitions to the left smoothly.
I am trying to build a bar graph that I can switch between the amount of data displayed based on a particular length of time. So far the code that I have is this,
var margin = {
top : 20,
right : 20,
bottom : 30,
left : 50
}, width = 960 - margin.left - margin.right, height = 500
- margin.top - margin.bottom;
var barGraph = function(json_data, type) {
if (type === 'month')
var barData = monthToArray(json_data);
else
var barData = dateToArray(json_data);
var y = d3.scale.linear().domain([ 0, Math.round(Math.max.apply(null,
Object.keys(barData).map(function(e) {
return barData[e]['Count']}))/100)*100 + 100]).range(
[ height, 0 ]);
var x = d3.scale.ordinal().rangeRoundBands([ 0, width ], .1)
.domain(d3.entries(barData).map(function(d) {
return barData[d.key].Date;
}));
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 + ")");
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(
"Total Hits");
svg.selectAll(".barComplete").data(d3.entries(barData)).enter()
.append("rect").attr("class", "barComplete").attr("x",
function(d) {
return x(barData[d.key].Date)
}).attr("width", x.rangeBand() / 2).attr("y",
function(d) {
return y(barData[d.key].Count);
}).attr("height", function(d) {
return height - y(barData[d.key].Count);
}).style("fill", "orange");
var bar = svg.selectAll(".barHits").data(d3.entries(barData))
.enter().append("rect").attr("class", "barHits").attr(
"x", function(d) {
return x(barData[d.key].Date) + x.rangeBand() / 2
}).attr("width", x.rangeBand() / 2).attr("y",
function(d) {
return y(barData[d.key].Count);
}).attr("height", function(d) {
return height - y(barData[d.key].Count);
}).style("fill", "red");
};
This does a great job displaying my original data set, I have a button set up to switch between the data sets which are all drawn at the beginning of the page. all of the arrays exist but no matter how hard I try I keep appending a new graph to the div so after the button click I have two graphs, I have tried replacing all of the code in the div, using the enter() exit() remove() functions but when using these I get an error stating that there is no exit() function I got this by following a post that someone else had posted here and another one here but to no avail. Any ideas guys?
What you are most likely doing is drawing a new graph probably with a new div each time the button is clicked, one thing you can try doing is to hold on to the charts container element somewhere, and when the button is clicked, you simply clear it's children and re-draw the graphs.
In practice, I almost never chain .data() and .enter().
// This is the syntax I prefer:
var join = svg.selectAll('rect').data(data)
var enter = join.enter()
/* For reference: */
// Selects all rects currently on the page
// #returns: selection
svg.selectAll('rect')
// Same as above but overwrites data of existing elements
// #returns: update selection
svg.selectAll('rect').data(data)
// Same as above, but now you can add rectangles not on the page
// #returns: enter selection
svg.selectAll('rect').data(data).enter()
Also important:
# selection.enter()
The enter selection merges into the update selection when you append or insert.
Okay, I figured it out So I will first direct all of your attention to here Where I found my answer. The key was in the way I was drawing the svg element, instead of replacing it with the new graph I was just continually drawing a new one and appending it to the #chart div. I found the answer that I directed you guys to and added this line in the beginning of my existing barGraph function.
d3.select("#barChart").select("svg").remove();
and it works like a charm, switches the graphs back and forth just as I imagined it would, now I have a few more tasks for the bargraph itself and I can move on to another project.
Thank you all for all of your help and maybe I can return the favor one day!
I have a very simple dataset. Just three values (could get more over time) looking something like this:
{a=10, b=20, c=30}
I try to visualize these values with something like a barchart. But instead of simple bars I want to use some fancy graphic drawn with an area.
I only get this to work at the moment by changing the data. I read in the data in a for loop and create a bigger data set by inserting an array for the area points for each datapoint. So I have an 3 dimensional array to feed to the vis which works just fine.
But it just seems wrong to me to change the data instead of the visualisation.
This is my code at the moment to create the areas:
var g = svg.selectAll("path.area")
.data(displayData) // dimension of data should be 3D
.enter()
.append("g")
.attr("class", "graph");
pathes = g.append("path")
.attr("class", "area") // not the cause of your problem
.attr("d", d3.svg.line().interpolate("linear-closed"))
.style("stroke", function(d) { return color(d.name); })
.style("stroke-width", 2);
Is there a way to drop in a function somewhere in this code to "inflate" each data point into a complete area in a clean way?
Something like:
.attr("d", d3.svg.line( function(d){ return inflateMyDataPoint(d); } ))
What should such a function return? And is this the right position for something like that?
Thanks!
Matthias
PS: Example pic:
You can always create a custom line generator. For a shape like you've shown, it might look something like this:
var w = 10; // width
function generator(y) {
var ys = scale(y);
return "M 0 " + ys + " L 0 " + (0.1*ys) + " " + (w/2) +
" 0 " + w + " " + (0.1*ys) + " 0 " + ys + "Z";
}
You can then do something like
g.append("path")
.attr("d", generator)
.attr("transform", function(d, i) {
return "translate(" + (i*w) + "," + (height - scale(d)) + ")";
});