I'm having a bit of a problem.
I'm using D3 to make a pie chart for an application I'm building. I basically it have it working, but I'm annoyed by one aspect of the chart. I've adapted the chart from here: http://jsfiddle.net/vfkSs/1/ to work with my application.
The data is passed in here:
data = data ? data : { "slice1": Math.floor((Math.random()*10)+1),
"slice2": Math.floor((Math.random()*10)+1),
"slice3": Math.floor((Math.random()*10)+1),
"slice4": Math.floor((Math.random()*10)+1) };
But somewhere in this file these slices are being ordered by value, which is not what I want.
The issue with this chart is that when it updates it adjusts all pieces of the chart to keep them in ascending order. For example the largest portion of the pie is always on the right, and smallest on the left. I would like these to remain in the order they are when the data is passed in.
This is buried a bit in the documentation.
pie.sort([comparator])
If comparator is specified, sets the sort order of data for the layout
using the specified comparator function. Pass null to disable sorting.
(bolding mine)
So, modify your .pie call to:
var cv_pie = d3.layout.pie().sort(null).value(function (d) { return d.value });
Updated fiddle.
Related
I'm working on a crossfilter between a line chart and choropleth. I recently got a much better understanding of the reduce method in dc.js, so I want to pass through some more metadata about each data point to my line chart and my choropleth. This is working really well for the line chart, and I now have a tooltip showing lots of information about each point.
For my choropleth, however, the transition to using reduce instead of reduceSum has really messed up my data. For example:
The value getting passed to the tooltip isn't the data I would expect, and I have no idea where the calculation is coming from (it almost seems like it's from the SVG path, or even the color accessor?)
As I toggle between different renderings of the choropleth, my choropleth changes, but the value on the tooltip stays exactly the same
The initial render of the choropleth is showing a fully blue map, so it seems like the initial value might be incorrect, anyway.
I'm trying to understand how I can identify the data point that's coming from the group, use that to render the choropleth based on a specific value (total_sampled_sales) and then pass that data to the tooltip so that each state's value and metadata can be displayed.
Also, any tips for debugging this type of issue would be greatly appreciated. As you may be able to see from my console.logs, I'm having a hard time tracing the data through to the tooltip. This is presumably the problem block:
us1Chart.customUpdate = () => {
us1Chart.colorDomain(generateScale(returnGroup()))
us1Chart.group(returnGroup())
}
us1Chart.width(us1Width)
.height(us1Height)
.dimension(stateRegion)
.group(returnGroup())
.colors(d3.scaleQuantize().range(colorScales.blue))
.colorDomain(generateScale(returnGroup()))
.colorAccessor(d => {
// console.log('colorAccessor:', d)
return d ? d : 0
})
.overlayGeoJson(statesJson.features, "state", d => {
// console.log(`geojson`, d, d.properties.name)
return d.properties.name
})
.projection(d3.geoAlbersUsa()
.scale(Math.min(getWidth('us1-chart') * 2.5, getHeight('us1-chart') * 1.7))
.translate([getWidth('us1-chart') / 2.5, getHeight('us1-chart') / 2.5])
)
.valueAccessor(kv => {
// console.log(kv.value)
if (kv.value !== undefined) return kv.value
})
.renderTitle(false)
.on('pretransition', (chart) => {
chart.selectAll('path')
.call(mapTip)
.on('mouseover.mapTip', mapTip.show)
.on('mouseout.mapTip', mapTip.hide);
})
https://jsfiddle.net/ayyrickay/f1vLwhmq/19/
Note that the data's a little wonky because I removed half of the records just for size constraints
Because of the data binding with choropleths, I'm now using the data that's passed through (specifically, the US State that was selected) and then identifying the data point in the crossfilter group:
const selectedState = returnGroup().all().filter(item => item.key === d.properties.name)[0]
So I have a returnGroup method that selects the correct choropleth group (based on some app state), gets the list, and then I filter to see which item matches the name property passed to the tooltip. Because filter returns an array, I'm just being optimistic that it'll filter to one item and then use that item. Then I have access to the full data point, and can render it in the tooltip accordingly. Not elegant, but it works.
After making several bar charts using enter, update, exit method in D3js, I wanted to try the same with a pie chart. I thought I applied selections correctly, but the pie chart won't update with the new data in JSON. I looked for similar examples online, but couldn't find one which involved an .on("click" method. I want users to compare the lifespans of humans and animals using a donut chart. I'm trying to implement the search tool through the database of animals right now.
here's what a data object looks like for the query Goat:
[{"Animal":"Male","Life_Span":73},{"Animal":"Goat","Life_Span":10}]
I'm having trouble with this code in particular:
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.Life_Span; });
//code for accessing data, etc
//enter remove selections
var path = svg.selectAll("path")
.data(pie(newdata))
var enterdata =
path.enter().append("path")
.attr("d",arc)
path.exit().remove()
enterdata.exit().remove()
I posted the full code on Plunkr here: http://plnkr.co/edit/3QSAPxQpju63tIXRd9p7?p=preview
A few weeks into learning d3js, I'm still struggling with enter,update exit selections even after reading many tutorials on the subject. I would really appreciate any help. Thanks
In D3 v4.x, you need to merge the update and enter selections:
var enterdata = path.enter()
.append("path")
.merge(path)
.attr("d",arc)
You don't need an exit selection because your data array has always 2 objects: except for the first time, your enter selection is always 0, and your exit selection is always 0.
I took the liberty of colouring the paths in different colours, according to their indices:
.attr("fill", (d,i) => i ? "teal" : "brown");
Here is your updated plunker: http://plnkr.co/edit/l6OzmxVfid9Cj7iv7IMg?p=preview
PS: You have some problems in your code, which I'll not change (here I'm only answering your main question), but I reckon you should think about them:
Don't mix jQuery and D3. You can do everything here without jQuery
Don't load all your CSV every time the user chooses an animal. It doesn't make sense. Instead of that, put the click function inside the d3.csv function (that way, you load the CSV only once).
Hi I am ordering the x values in my bar chart with .ordering. It orders correctly. However on filtering on other linked charts the ordering doesn't change. How do I achieve this behaviour?
Also ordering for me only works when I am overriding the default groupX.all() function with
groupX.all = function() {
return groupX.top(Infinity);
}
How can I make my bar chart order itself everytime it's redrawn?
How about this (untested):
chart.on('preRedraw', function() {
chart.rescale();
});
Since the ordering is implemented via the X scale, this should get the chart to recompute the scale each time.
I would like to create a d3-based plot which graphs a plot within a tooltip. Unfortunately, I haven't found any examples on the web. Here is a sample JSON file.
[{"x":[0.4],
"y":[0.2],
"scatter.x":[0.54,0.9297,0.6024,-1.9224,2.2819],
"scatter.y":[0.4139,1.1298,-0.1119,2.3624,-1.1947]},
{"x":[0.1],
"y":[0.9],
"scatter.x":[-0.8566,-0.5806,-0.9326,0.8329,-0.5792],
"scatter.y":[-0.5462,-0.7054,1.0264,-3.4874,-1.0431]}]
The idea is to have a scatter plot for (x,y) coordinates first. However, when one mouses over a point, a different scatter plot within a tooltip appears based on [scatter.x, scatter.y] coordinates for that respective point.
I can do the scatter plots separately but have been struggling to put them together. Could anyone shed some light on this and/or provide a minimal example?
This was too long for a comment but I'm not certain if it's the answer you were looking for. One of the issues you might find is that your nested data is formatted differently-- one uses JSON objects with x and y, while the other uses two arrays of points.
My solution to this would be to create an extensible function:
function makeScatterPlot(elem, width, height, data, fill)
elem, width, height, and data are the core parameters: which element to attach the chart to, the size of the chart, and the data for the chart (in the JSON object format).
This function would generate all necessary items for the chart and add the chart to the provided element.
Then you want to bind to mouseover of your main chart, and in that function you'll have to do a bit of data modification to re-organize the two arrays into the JSON object structure.
function mainMouseover(d){
var newData = [];
for (var i = 0; i < d["scatter.x"].length; i++){
var t = {x: [0], y: [0]};
t.x[0] = d["scatter.x"][i];
t.y[0] = d["scatter.y"][i];
newData.push(t);
}
var newG = mainG.append("g").attr("transform", "translate(200,200)");
makeScatterPlot(newG, 100,100, newData, "red");
}
Of course, you would modify the translate to match wherever you want your tooltip to be.
Putting this all together you get the following (very crude) fiddle. Hover over either of the black dots to see the sub-chart. Obviously this needs quite a bit of work to be a solid example (i.e. remove the sub-chart on mouseout), but hopefully it will set you in the right direction.
If the tooltip chart is significantly different styling-wise compared to your main chart it may not be the best idea to use an extensible function, and you could just create another custom function instead.
I try to reuse the example of 'scatter matrix with brushing': http://bl.ocks.org/mbostock/4063663
It seems that the code is not directly reusable with another csv. Scales seems to be somehow hard coded or so: i change the csv by adding 10 to 75% of the first column values, and the xscale is not directly updated.
To visualize the problem, see the fork of the mbostock gist: http://bl.ocks.org/fdeheeger/7249196
I cannot figure out where/how the scale is computed or updated in the javascript code.
Any advice from a d3 expert?
The scales are computed dynamically -- the problem is that the numbers in the CSV are parsed and processed as strings and not numbers. This is also the case in the original block, but there it doesn't matter because the ordering of the strings is the same as the ordering of the numbers.
All you need to do to fix this is parse the strings to numbers:
domainByTrait[trait] = d3.extent(data, function(d) { return +d[trait]; });
The plus makes all the difference here. Complete example here.