Brushing on ordinal data does not work - javascript

I really like this graph and its functionality and it is perfect for what I want/need. The only thing I need to change is I need it to allow ordinal data on the y-axis and I cannot seem to get that to work (I am a beginner).
When I change the y scale from linear to ordinal:
yscale[k] = d3.scale.linear()
.domain(d3.extent(data, function(d) { return +d[k]; }))
.range([h, 0]));
to
yscale[k] = d3.scale.ordinal().rangePoints([h, 0]),
yscale[k].domain(data.map(function(d) { return d[k]; })))
Brushing still shows up and works by itself but it does not filter leaving the selected lines. No lines show up unless I move it to the very top of the axis then, all or mostly all show up. When I stepped through the code with firebug it looked like it was just not getting the lines that were in the brush area but all(?)... and I can't seem to figure out. :(
If anyone could help out with this (especially all the places I have to change and how), I would love to get this working and learn what I am doing wrong :-\

Brushing an ordinal axis returns the pixels, while brushing a quantitative axis returns the domain.
https://github.com/mbostock/d3/wiki/SVG-Controls#wiki-brush_x
The scale is typically defined as a
quantitative scale, in which case the extent is in data space from the
scale's domain; however, it may instead be defined as an ordinal
scale, where the extent is in pixel space from the scale's range
extent.
My guess is that you need to work backwards and translate the pixels to the domain values. I found this question because I'm trying to do the same thing. If I figure it out, I'll let you know.
EDIT: Here's an awesome example to get you started.
http://philau.willbowman.com/2012/digitalInnovation/DevelopmentReferences/LIBS/d3JS/examples/brush/brush-ordinal.html
function brushmove() {
var s = d3.event.target.extent();
symbol.classed("selected", function(d) { return s[0] <= (d = x(d)) && d <= s[1]; });
}
He grabs the selection extent (in pixels), then selects all of the series elements and determines whether they lie within the extent. You can filter elements based on that, and return data keys or what have you to add to your filters.

There is an example of an ordinal scale with brushing here:
http://bl.ocks.org/chrisbrich/4173587
The basic idea is as #gumballhead suggests, you are responsible for projecting the pixel values back onto the input domain. The relevant snippet from the example is:
brushed = function(){var selected = yScale.domain().filter(function(d){return (brush.extent()[0] <= yScale(d)) && (yScale(d) <= brush.extent()[1])});
d3.select(".selected").text(selected.join(","));}

Related

How to format array of values to form a distribution for google-charts histogram?

I have 1000 values in no particular order but I'd like to format them into a normal distribution to plot on a histogram using google-charts.
I've tried using d3.js and I got it working just based off some examples but it looks extremely ugly and I don't have enough time to learn d3 in and out to get the results I want. Google-charts visual format are great.
The problem is google-charts expects data in a format where each value has a name along with headers. So when I organized it into this:
'dsSample1': [
['price', 'number'],
['price', 11386.057139142767],
['price', 27659.397260273952],
['price', 44159.39726027395],
...
from
'dsSample2': [
11386.057139142767,
27659.397260273952,
44159.39726027395,
28026.04112639835,
...
google charts works, but I get the following:
This is as close as I've come to getting it working in d3: https://jsfiddle.net/0jtrq17x/1/. It works but it's extremely ugly.
I've managed to arrange the array data into bins using some d3 code but it is imcompatible with google-charts and I don't know to make it compatible, and also don't know how to format the data so it plays nice with google-charts histogram
this code
var values = this.hypo.dsSample2.map(x => {
return x + 128608.42487322348
})
var max = d3.max(values)
var min = d3.min(values)
var x = d3.scale.linear()
.domain([min, max])
.range([0, 800]);
var histGenerator = d3.layout.histogram()
.bins(x.ticks(100))
(values)
this.data1 = histGenerator
returns this array transformation
My problem is I don't know how to massage my array of data so I can get something like this in google-charts:
there are two data formats for the google charts version.
a single series format, with the names,
or a multi-series format, with just the numbers.
it is ok to use the multi-series format with a single series.
so, assigning names is not required.
but you will have to convert each value to its own array.
'dsSample1': [
[11386.057139142767],
[27659.397260273952],
[44159.39726027395],
...
from
'dsSample2': [
11386.057139142767,
27659.397260273952,
44159.39726027395,
...
you can use the map method to format the data.
dsSample.map(function (value) {
return [value];
});
see following fiddle...
https://jsfiddle.net/x684f1vs/
I know you have decided against D3, but since your question is still tagged with d3.js, I will post an answer using D3 anyways :)
I have made an updated JSFiddle, with an adaption of your code:
https://jsfiddle.net/w7r80cfo/1/
In short, to manipulate this histogram, look to the following lines:
1038 and 1039 to change the dimensions (width and height respectively) of the visualization. The values given are in pixels.
1049 to change the number of buckets for you histogram. Currently it is set to 100.
1083 to change the width of the individual bars. Currently, I've set it to 0.25 of the space calculated for each bar. If you e.g. change 0.25 to 1 the bars will be so wide, they will be drawn right next to each other.
1085 to change the color of the bars. Currently they are given a darker shade of red the higher number of values they represent. If you want e.g. just blue, change the line to .attr("fill", "steelblue")
Play around with these values and see if you can get to a chart that is close to what you want.
To elaborate a bit on the changes I've made, they consist mainly of the following:
Line 1038: lowered the width to 600.
Line 1073: updated to position the visualization correctly:
.attr('transform', `translate(${margin.left},${margin.top})`);
Line 1083: lowered the width of the bars by multiplying by 0.25:
.attr("width", (x(data[0].dx) - x(0)) * 0.25)
Other than that I have removed the following code to remove the text labels, as they indeed made the chart look messy:
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 "$" + d3.format(",.2f")(d.x); });
Besides this, I have added an y axis and changed the way the axes are drawn in order to make them look a bit nicer. I can go into detail about these changes, but I think they are of lesser interest to your goal.
Hope this helps!

D3.js Brush & Zoom to Rescale Y-Axis By Zoomed Range's Values

What would be the most elegant way to autoscale Y-axis range/domain according to zoome range's values, when modifying this demo?
https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172
There must be some d3-zoom methods that can accomplish accessing zoomed range's values, but haven't yet figured out which those would be...?
I don't know what's the most elegant way (until someone shows it). However, here is my solution.
First, we filter the data according to the zoom:
var filteredData = data.filter(d=>d.date > x.domain()[0] && d.date < x.domain()[1]);
Then, we change the y domain accordingly:
y.domain([0, d3.max(filteredData, function(d) { return d.price; })]);
Here is the demo, zoom in and out to see the y axis changing:
https://bl.ocks.org/anonymous/raw/9f8c2edcb5950cac61f1bc3873886ec5/
This other version avoids NaN when you zoom in too much:
https://bl.ocks.org/anonymous/raw/56fa7fe37596f753db74fdad58ba6725/
PS: I had to move some functions (due to scope issues) in order to access data inside the function zoomed.

Automatic Date Labeling for NVD3 Graphs

I want the date labels to automatically be calculated, appear, and disappear when I change the focus range so that they don't overlap.
I am using a MultiBar graph with a focus chart with the default ordinal scale for nv.models.multiBar(). When I use .ticks(availableWidth / 100 ) on the xAxis, it seems to generate a tick label for EVERY date, or at least a very large number of them:
On nv.models.lineWithFocusChart(), the labels are automatically reduced to fit in a space. This could be because it uses the scale for nv.models.scatter() which is a d3.scale.linear(), but I'm not sure. I tried creating my own scale with the following:
x = d3.scale.ordinal() //as well as x = d3.scale.linear()
.domain(d3.extent(data.map(function(d) {
return d.values.map(function(d,i) {
var X = getX(d,i);
return X.getTime();
});
})))
.range([0, availableWidth]);
I get the following for an ordinal scale:
and no labels for a linear scale. Will this approach work? If so, what am I doing wrong?
On nv.models.multiBarChart(), there is a .reduceXTicks(BOOLEAN) option but this only applies to multiBarChart and there doesn't seem to be an easy way to add it to nv.models.multiBar(). Can I somehow use this?
If there is anything I haven't tried please let me know. I don't want to calculate the labels myself and specify them using .tickValues()
The solution was in fact to use d3.scale.linear() for the x axis. What I tried above didn't work because I was specifying the whole domain of the context chart, when I needed to specify the min and max of the current selection.
In chart(selection) {...}, I put
x = d3.scale.linear()
.range([0, availableWidth]);
and in onBrush(), I put x.domain([new Date(extent[0]), new Date(extent[1])]);, where extent contains the min and max dates of the selection in milliseconds.

d3 x axis too short for scatterplot content

I'm having trouble with my X axis width on a D3 scatterplot - what's happening is that my x-axis isn't filling the space allotted, that the Data happily fill. JSfiddle here: http://jsfiddle.net/u4cGJ/
I've defined my d3 scale's output range thusly:
.range([padding, svgWidth - padding]);
and the output range of points on the scatterplot perfectly lines up with this, but the x-axis doesn't - it stops short of the range of points displayed, - it's doing exactly what I tell it to do, and yet, as the svg extends farther out, the data fill in that space too, leaving a section of data that are visible, but not being placed in context of an axis.
Thanks for any help you can offer!
Likely the problem is that your defined domain doesn't include the full extent of your data. The scale domain/range are used to map ranges of data values so that if your domain is [0,10] and your range is [0,100], you will get values like range(0) = 0, range(1) = 10, range(2) = 20... range(10) = 100 (depending on the kind of scale used).
Since it's just mapping domain to range, if you give it a value that it can't map, you aren't likely to get a value inside of your range's extent. Eg. if you do range(11) you won't get a value between 0 and 100. Since the range value is what your axis and plot are likely using to build the actual svg, the points that fall outside of your domain are going to end up off your plot (or NaN or something).
Try deriving the domain from the data itself. D3 has min, max, and extent functions to make this easy for you. If you have an array of point objects, you can use the accessor as a function to provide the right value to use in the calculation.
Here's an example:
var data = [{x:1, y:1}, {x:2, y:4}, {x:3, y:2}, {x:4, y:1}, {x:5, y:2}];
var xExtent = d3.extent(data, function(d) { return d.x; });
var yExtent = d3.extent(data, function(d) { return d.y; });
See the jsFiddle: http://jsfiddle.net/reblace/c9qw8/
Looking at your fiddle, it looks like there's an error in the logic where you're using the wrong domain for what's actually being plotted. If you get rid of the default min and max stuff, it seems to correct the problem you're describing:
function makeScales(xAxisRepresents, domainMinOverride, domainMaxOverride) {
var domainMin = d3.min(dataset, function datumToValueTransformer(datum) { return datum[xAxisRepresents]; });
var domainMax = d3.max(dataset, function datumToValueTransformer(datum) { return datum[xAxisRepresents]; });

D3 linechart, can't edit the amount of ticks with an ordinal scale?

I asked a question before about d3, and they suggested me to use an ordinal scale, this would solve my problems. Indeed it solved my problems, but know I'm stuck with another issue...
It draws perfectly, but my X-axis is full of text.
As an example, I want:
1900 1904 1908 1912 ...
but I got:
190119021903190419051906. As you can see this is not clear. (this is just an example, if there were only dates I could use another scale).
Everywhere I looked they talk about axis.ticks(number). But this doesn't work. Nothing happens and I still get the same result.
I hacked a result to get less results on the x-axis:
var str = [];
var i = 0;
while(i < data.length) {
str.push(data[i].age);
i=i+8;
}
x.domain(str);
But if I do this it creates a random line and doesn't draw it perfectly anymore. Don't know how to solve this.. It's a simple line chart, nothing difficult, the only difficulty (for me) is the ordinal scale...
Hope someone can help me out.
this is how my x and x-axis is defined:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width-150],1);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
without the while-loop (the nasty hack), I just had the following line defining the x.domain:
x.domain(data.map(function(d) { return d.age; }));
Have a look at the documentation for axes, in particular the ticks() function. You can use it (or tickValues()) to control how many (and what) values you want to show.
If you're working with dates, you might want to use a time scale instead of the ordinal one. In particular it will allow you to control the ticks in a more meaningful way, e.g. specify that you want ticks every five years.

Categories

Resources