D3 time and date histogram - javascript

I'm attempting to make a histogram using primarily time and date data, provided in a json file (along with other info) in this format: 2014-03-01 00:18:00. I've looked at http://bl.ocks.org/mbostock/3048450 as an example, but I haven't managed to crack it. The key part seems to be this:
var data = d3.layout.histogram()
.bins(x.ticks(20))
(dataset.timestamp);
When I view my code in the browser it gives "TypeError: data is undefined", and refers to d3.v3.js line 5878.
Assuming I fix that error, the next place it may stumble is the axis formatting:
var formatDate = d3.time.format("%y-%m-%d %h:%m:%s");
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatDate);
Will the format syntax correspond correctly to my time and date format?

I don't think that the histogram layout accepts non-numeric input (I could be wrong). One option would be to convert the dates into the number of milliseconds since 1970 by parsing and using getTime():
var formatDate = d3.time.format("%Y-%m-%d %H:%M:%S");
var data = d3.layout.histogram()
.bins(x.ticks(20))
.value(function(d) {return formatDate.parse(d.timestamp).getTime()})
(dataset);
You'll need to make sure that the x scale (as in x.ticks(20)) has a domain based on the millisecond data.

So I figured it out, thanks to the helpful answers here. First off, the json data is acquired:
d3.json("inkmarch.json", function(error, json) {
if (error) return console.warn(error);
dataset = json;
Then I specify a formatting variable specific to my date formatting:
var formatDate = d3.time.format("%Y-%m-%d %H:%M:%S");
I map the re-formatted dates to another var:
mappedSet = (dataset.map(function(d) {return formatDate.parse(d.timestamp).getTime()}))
And finally I can make a proper histogram dataset.
var data = d3.layout.histogram()
.bins(x.ticks(31))
.value(function(d) {return formatDate.parse(d.timestamp).getTime()})
(dataset);
(31 ticks since this is monthly data from March). I did away with the d3.time.scale since they were integers anyway, so my scales look like such:
var x = d3.scale.linear()
.domain([d3.min(mappedSet), d3.max(mappedSet)])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
(Still not sure what the function in the y domain does). The svg and bar vars look exactly like the example I linked in my question post, as do the 'rect' and 'text' bars (except I changed width of rect and x position of the text to fixed values since the example formulas were giving hideous negative values).
Thanks again for the help, I'm sure I'll have more d3 questions in the near future.

Related

Non continuous date domain using scaleTime()

Preface: I've gone through all other stackoverflow questions relating to this problem I could find, which are outdated or recommend using a ordinal scale instead. Including this one: D3 Non-Continuous Dates Domain Gives Gaps on X-Axis
which describes my problem as well.
Goal: I am trying to create a candlestick chart with zoom in/zoom out and panning. Currently the chart is working as intended, minus the x-axis (which contains dates/times of each candlestick).
I want the x axis to function like it does with scaleTime(), where it shows years/months, and when you zoom in it shows the date/time, depending on the time interval. I know timeScale() is continuous, but I need the functionality of the zooming in and out.
Problem: Gaps are included in the x-axis since when I set the domain for the x-scale and x-band, I am using the minimum and maximum dates in the dataset (named 'prices').
Code (d3js v7):
Works but x-scale is not dates, but decimal values from -1 to dates.length:
var xScale = d3.scaleTime()
.domain([-1, dates.length])
.rangeRound([0, w]);
Works x-scale is dates, but includes gaps for weekends and holidays:
var xScale = d3.scaleTime()
.domain([xmin, xmax])
.rangeRound([0, w]);
Doesn't work, x-scale is blank, coordinates are messed up:
var xScale = d3.scaleTime()
.domain(prices.map(r => r.t))
.rangeRound([0, w]);
I calculate the x coordinates for my candle bodies for (map) and [xmin,xmax] as:
.attr('x', (d, i) => xScale(d.t) - xBand.bandwidth())
or for domain([-1, dates.length])
.attr('x', (d, i) => xScale(i) - xBand.bandwidth())
xBand is declared as:
let xBand = d3.scaleBand()
.domain(d3.range(-1, dates.length))
.range([0, w])
.padding(0.2);
Another solution I can think of is to somehow convert the demical values from the domain in the first xScale example to function like the scaleTime() scale using tickFormat(), but I'm not sure how I would go about doing that. I have already converted them from decimal to dates using .tickFormat(prices.map(d => new Date(d.t))); but don't know where to go from there.
Questions: Can you pass an array of values as the domain? Or is it just a min and max value, since domain is defined as boundaries within which your data lies?
Am I passing the array mapping correctly? Is this allowed?
Finally, how can I set my domain to the array of dates I have without including gaps on the chart?

Plotting heatmap with available attributes instead of range D3 React

I'm working on a heatmap which basically plots the graph between taxIDs and KeywordNames from an external JSON. While I'm able to plot the values I see many blank spaces on the graph and clueless how I can plot them with the available data.
Here's the link to codesandbox: https://codesandbox.io/s/40mnzk9xv4
On the X-Axis I'm plotting the TaxIDs which are being calculated within the given range. I did try using the function rangeBands() but I get an error everytime.
Its the similar case with Y-Axis where I'am plotting the keywordIDs which are also being calculated within a range. I'm trying to print all the KeywordNames on Y axis and all taxIDs on the X-Axis and plot their corresponding spectracount on graph.
Please help me where have I gone wrong.
The output I'm looking for is something similar to this: https://bl.ocks.org/Bl3f/cdb5ad854b376765fa99
Thank you.
Some things to help you get you one your way:
First, your scales should use scaleBand(), not scaleLinear(), as they have discrete domains (i.e. categories of something, rather than continuous)
Second, your scale domains is taking every value of taxId and keywordName in your data as a possible value. But some values are repeated more than once. You need to be filtering them so you only have unique values. So your scale code should be:
const xValues = d3.set(data.map(d => d.taxId)).values();
const yValues = d3.set(data.map(d => d.keywordName)).values();
const xScale = d3.scaleBand()
.range([0, width])
.domain(xValues); //X-Axis
const yScale = d3.scaleBand()
.range([0, height])
.domain(yValues); //Y-Axis
Finally, your code that places the heatmap tiles needs to be calling the scale functions so it works out the position of each rect correctly:
chart.selectAll('g')
.data(data).enter().append('g')
.append('rect')
.attr('x', d => { return xScale(d.taxId) })
.attr('y', d => { return yScale(d.keywordName) })
That should get you most of the way there. You'll want to also reduce cellSize and remove the tickFormat calls on the axes as they are trying to convert your text labels to numbers.

D3 v4 returning error for scaleTime when passing in Date object

I am trying to create a simple bar chart where the x axis is formatted with dates. I have defined my x like so,
var minDate = new Date(data[0][0]);
var maxDate = new Date(data[274][0]);
var x = d3.scaleTime()
.domain(minDate, maxDate).range([0, width]);
However, I get an error when I try to call this from my chart
chart.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', function(d){
return x(new Date(d[0]));
})
The error says
Error: attribute x: Expected length, "NaN".
Not really sure what I'm doing wrong. Do date objects still work in D3 v4 with a scaleTime?
Here is a link to the dataset if anyone wants to take a look
https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json
Here is a link to the codepen where I am working on this
http://codepen.io/redixhumayun/pen/ZBdmQp?editors=0010
In d3 scales, domain takes an array as argument. Therefore, it should be:
.domain([minDate, maxDate])

Add time parser to axis in interactive scatterplot using D3js

I am making a scatterplot using D3.js and I am unable to apply a proper time scale to the X axis. All my data is within the same year (2016), in a 3 months span.
I usually do this in a different way, and I want to learn what I am doing wrong in this one, which has a different code structure as I usually use in D3.
Here is the code in JsBin
This is X axis code:
var xValue = function(d) {
return d.datadois;
},
xScale = d3.time.scale(),
xMap = function(d) {
return xScale(xValue(d));
},
xAxis = d3.svg.axis().scale(xScale).orient("bottom").ticks(10, ".f");
Wonder how can I apply the time scale properly, to render the months in my data.

custom ticks on an ordinal scale d3

I've been creating some charts to plot intra-day data from financial results. Often this is a value generated every ten minutes. This varies but its a good example. Therefore there are large periods of time I won't get information, eg when markets are close over weekend and between 5:00pm in the evening and 9:00pm in the morning. I've tried created a custom time scale for the x-axis but in the end the best result is to just use an ordinal scale. it works well and gives the result that I and the people reading the chart want ie, no gaps in the line plot and evenly space data points. (Its the convention)
My question is how do I know plot custom ticks on this xAxis in the correct place, given that I generate them in an array called ticks.major. The example below shows how I generate the axis and there are the correct number of days. But they all are being plotted at the beginning of the graph. Any help appreciated thanks.
var xScale = d3.scale.ordinal()
//var xScale = scaleWeekday()...custom timescale no longer used
.domain(xDomain)
.rangeBands([0,(plotWidth-yLabelOffset)])
var xAxis = d3.svg.axis()
.scale(xScale)
//.tickValues(ticks.major)//used to create tick d3 time scale axis
.tickFormat(function (d,i) {
return ticks.major[i]
})
.tickSize(yOffset/2)
.orient("bottom");
var xLabel=plot.append("g")
.attr("class",media+"xAxis")
.attr("transform",function(){
if(yAlign=="right") {
return "translate("+(margin.left)+","+(plotHeight+margin.top)+")"
}
else {return "translate("+(margin.left+yLabelOffset)+","+(plotHeight+margin.top)+")"}
})
.call(xAxis);
it looks like this:
I think the mistake I'm making is that by using the tick.major array its applying the tick value to the first 12 dates that are passed bacause thats all thats in the tick.major array. Then because there are no more dates in the tick.majore array it has no labels for any further date in the series. Its better to apply a test in the tickFormetter to see if the current day at a particular datapoint is different from the day at the previous datapoint. Then return a tick. like this
.tickFormat(function (d,i) {
if(i>0) {
var day=d.getDay()
var yesterday=data[i-1].date.getDay()
console.log(day,yesterday)
if(day!=yesterday) {
return d
}
}
})
The returned d needs a bit of date formatting to make it readable

Categories