Making a calendar with d3 - javascript

i am trying to build a plugin to display a year view of the events on a google calendar account, i am trying to build this view using D3 and fetching the data from the google calendar API (this part sounds easy so far), but i'm stuck trying to actually build the view in d3, here is what i have so far:
My code :
var margin = {top: 40, right: 40, bottom: 40, left: 40},
width = 960,
height = 500;
var x = d3.time.scale()
.domain([new Date(2013, 0, 1), new Date(2014, 0, 1)])
.range([0, width])
var y = d3.time.scale()
.domain([new Date(2013,0,1), new Date(2013, 0,31)])
.range([0, height])
var xAxis = d3.svg.axis()
.scale(x)
.orient("top")
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(d3.time.days, 1)
.tickFormat(d3.time.format('%e'))
var svg = d3.select(".container").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 + ")");
function makeXaxis() {
return d3.svg.axis()
.scale(x)
.orient("top")
}
function makeYaxis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(d3.time.days, 1)
.tickFormat(d3.time.format('%e'))
}
svg.append("g")
.attr("class", "x axis")
// .attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(0,0)")
.call(yAxis);
svg.append("g")
.attr("class", "grid")
.call(makeYaxis()
.tickSize(-width, 0, 0)
.tickFormat("")
.tickPadding(8)
)
svg.append("g")
.attr("class", "grid")
.call(makeXaxis()
.tickSize(-height, 0, 0)
.tickFormat("")
)
What it renders:
actual view calendar
What i want to achieve:
goal calendar
There are a few problem with my code,
the first being that my y domain is an arbitrary month of 31 days, i don't know if my data will place itself on the graph well if it is a time scale, should i use a linear scale of 31 ?
How can i just render January...December without the 2013 and 2014
How can i display the months in the middle top of each row instead of displaying them on every tick ?
Well , i am not going to ask for more considering i am already asking for alot.
Thanks everyone, i am totally new to d3, i have read lots of tuts tho.

My approach (not the only way):
Use linear numerical domains for both axes. In other words:
x.domain( [0, 11] ); // months, zero-indexed
y.domain( [1, 31] ); // days of month
To render the months properly, you will then have to do something kooky like:
var monthFormatter = d3.time.format( "%B" ); // %B = Month name
function makeYaxis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat( function(d) { return monthFormatter( d.date ) } )
}
As for alignment of these values, this https://groups.google.com/forum/?fromgroups=#!topic/d3-js/1gCrn0taKw8 describes how it's a non-trivial problem. You may be best to tinker with adjusting the x-values manually.
I don't see the code used to render the data on screen, but you can use something like:
svg.selectAll( rect ).data( myData ).append( "rect" )
.attr( "x", function(d) { return x( d.date.getMonth() ); } )
.attr( "y", function(d) { return x( d.date.getDate() ); } )
I imagine that having 'stacked' data (side-by-side) will be problematic, but we'll deal with that later.

Related

D3.js linechart - controlling x-axis with dates

I have created a linechart with D3.js, but can't seem to figure out how to control the X-axis completely.
You can see my example her: http://codepen.io/DesignMonkey/pen/KdOZNQ
I have sat the ticks count for the x-axis to 3 days, and I have an Array with a range of 31 days, that should show a day in each end of the x-axis and skip to every third day. But for some reason when the a-axis pass the 1st in the month, it shows both 2015-08-31 and 2015-09-01 and doesn't skip to 2015-09-03 as it is supposed to.
My code for the linechart is here:
// Set the dimensions of the canvas / graph
let margin = {top: 30, right: 20, bottom: 30, left: 40},
width = 330 - margin.left - margin.right,
height = 180 - margin.top - margin.bottom;
// Set the ranges
var x = d3.time.scale().range([0, width]).nice(10);
var y = d3.scale.linear().rangeRound([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom")
.ticks(d3.time.days, 3)
.tickFormat(d3.time.format('%e'))
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10)
var yAxis = d3.svg.axis().scale(y)
.orient("left")
.ticks(5)
.innerTickSize(-width)
.outerTickSize(0)
.tickPadding(10)
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); });
// Adds the svg canvas
let svg = d3.select(template.find(".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 + ")");
// For each line
data.forEach((item) => {
// Scale the range of the data
x.domain(d3.extent(item.data, function(d) {
if(d.value != undefined)
return d.date;
}));
// Create a perfect looking domainrange to the nearest 10th
y.domain([
Math.floor(d3.min(item.data, function(d) {
if(d.value != undefined)
return d.value;
})/10)*10
,
Math.ceil(d3.max(item.data, function(d) {
if(d.value != undefined)
return d.value;
})/10)*10
]);
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
// Add only points that have value
svg.append("path")
.attr("class", "line color-"+ item.colorClass)
.attr("d", valueline(item.data.filter((pnt) => pnt.value != undefined)));
});
Can somebody tell me what I'm doing wrong here? :)
/Peter
UPDATE:
I found out it's like, that it want to show the new month. See this pen: http://codepen.io/DesignMonkey/pen/jbgYZx
It doesn't say "Septemper 1" but only "Septemper" like it wants to label the change of month. How do I disable this? :)
Solution:
var count = 0;
var tickRange = data[0].data.map((item) => {
count = (count == 3) ? 0 : count+1;
if(count == 1) {
return item.date;
}
})
.filter((d) => d != undefined);
and then:
var xAxis = d3.svg.axis().scale(x)
.orient("bottom")
.ticks(d3.time.days, 3)
.tickValues(tickRange)
.tickFormat(d3.time.format('%e'))
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10)
Thanks :)

what scale to use for representing years only on x axis in d3 js

I have been developing an area chart for year(x axis) vs Revenue (y axis) in D3 Js.The data is as:
localData=[
{"Revenue":"4.5","Year":"2011"},
{"Revenue":"5.5","Year":"2010"},
{"Revenue":"7.0","Year":"2012"},
{"Revenue":"6.5","Year":"2013"}
]
I want year at x axis and revenue at y axis for an area chart.Currently I am using time scale for x axis but i dont know how to use it as I have not date format I have only Years to represent.
My Current code is:
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 500 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var area = d3.svg.area()
.x(function (d) { return x(d.Year); })
.y0(height)
.y1(function (d) { return y(d.Revenue); });
$("#chartArea").html("");
var svg = d3.select("#chartArea").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 + ")");
x.domain(d3.extent(localData, function (d) { return d.Year; }));
y.domain([0, d3.max(localData, function (d) { return d.Revenue; })]);
svg.append("path")
.datum(localData)
.attr("class", "area")
.attr("d", area)
.attr("fill",color);
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("Revenue (M)");
Currently I am getting on my X axis as .011,.012,013,.014 I need as 2011,2012,2013,2014
I am new to D3 js so dnt know much about how to use scales??Please Help anyone..Thanks in advance.
Just add tick Format to your x Axis definition:
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%Y")); // <-- format
In v4, it'd be something like this:
d3.axisBottom(x).ticks(d3.timeYear.every(1))
huan feng is right. The time scale is treating your year(implicitly converted to an int) as timestamps. To force the scale to operate on the year, create Date objects specifying the year in it. Basically change the following line:
x.domain(d3.extent(localData, function (d) { return d.Year; }));
to
x.domain(d3.extent(localData, function (d) { return new Date(parseInt(d.Year),0); }));
You may then use Klaujesi's solution to change the tickFormat.

D3js inverting graphs with y-values between 9 and 10

So I'm dynamically creating a bunch of simple line charts with D3 and everything is going well, but for some reason charts with ranges that go from 9-10 get inverted and look absolutely terrible/do not function properly.
the first one, the values are upside down
this one is fine...
Here is some code...
var dataRange = d3.extent(quoteObjects, function(d){ return d.close });
var dateRange = d3.extent(quoteObjects, function(d){ return d.date });
// Set chart variables
var vis = d3.select("#"+type),
WIDTH = $('#chart-box').width(),
HEIGHT = $('#'+type).innerHeight(),
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 60,
},
// set scales
xScale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]).domain(dateRange),
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain(dataRange),
// create displayed axis
xAxis = d3.svg.axis()
.scale(xScale)
.tickValues( xScale.ticks(6) )
yAxis = d3.svg.axis()
.scale(yScale)
.tickValues( yScale.ticks(6) )
.orient("left");
console.log("WH", WIDTH, HEIGHT);
if (type == "intraday"){
xAxis.tickFormat(d3.time.format("%H"))
}
// append x axis
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.top) + ")")
.call(xAxis);
// append y axis
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
// create line based on "close" values
var lineGen2 = d3.svg.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.close);
})
.interpolate("basis");
// append "close" line
vis.append('svg:path')
.attr('d', lineGen2(quoteObjects))
.attr('stroke', '#931a28')
.attr('stroke-width', 3)
.attr('fill', '#222');

Why d3 time scale only shows me 00:00?

I'm new to d3 and I'm trying to do some data visualization with it. I found some examples about how to create a time scale in d3, but when I followed the examples and try to create the time scale, it failed. I was frustrated because I couldn't figure out where it went wrong... the example is like this:
how to format time on xAxis use d3.js
So my code is like this:
boxplotdata =[]
boxplotdata.push(
{"datetime":"2013-10-30 01:47",length: 500, start:100,deep1_a:130,deep1:50,deep2_a:200,deep2:60,deep3_a:280,deep3:50,deep4_a:350,deep4:60},
{"datetime":"2013-10-31 01:45",length: 600, start:200,deep1_a:230,deep1:60,deep2_a:300,deep2:60,deep3_a:380,deep3:50,deep4_a:450,deep4:60},
{"datetime":"2013-11-01 02:11",length: 550,start:150,deep1_a:180,deep1:50,deep2_a:250,deep2:60,deep3_a:350,deep3:50,deep4_a:410,deep4:60},
{"datetime":"2013-11-02 01:59",length: 500,start:160,deep1_a:190,deep1:80,deep2_a:300,deep2:60,deep3_a:370,deep3:50,deep4_a:430,deep4:60},
);
//SET MARGIN FOR THE CANVAS
var margin = {top: 30, right: 10, bottom: 10, left: 10},
width = 960 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d %H:%M").parse;
//SET X AND Y
var x = d3.time.scale()
.domain([0,11])
.range([50, width]);
var y = d3.time.scale()
.domain([new Date(boxplotdata[0].datetime),d3.time.day.offset(new Date(boxplotdata[boxplotdata.length-1].datetime),1)])
.rangeRound([20, height-margin.top- margin.bottom]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("top")
.tickFormat(d3.time.format("%H:%M"))
//.ticks(d3.time.minutes,15)
//.tickPadding(8);
var yAxis = d3.svg.axis()
.scale(y)
.orient('right')
.ticks(d3.time.days,1)
.tickFormat(d3.time.format('%m-%d'))
.tickSize(0)
.tickPadding(8);
var line = d3.svg.line()
.x(function(d) { return x(d.datetime); });
var w=960,h=1000;
d3.select("#chart").selectAll("svg").remove(); //Old canvas must be removed before creating a new canvas.
var svg=d3.select("#chart").append("svg")
//.attr("width",w).attr("height",h);
.attr("width",w+margin.right+margin.left).attr("height",h+margin.top+margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
boxplotdata.forEach(function(d) {
d.datetime = parseDate(d.datetime);
});
x.domain(d3.extent(boxplotdata, function(d) { return d.datetime; }));
bars = svg.selectAll("g")
.data(boxplotdata)
.enter()
.append("g");
some drawing codes here..., and at last:
svg.append("g")
.attr("class", "x axis")
//.attr('transform', 'translate(0, ' + (height - margin.top - margin.bottom) + ')')
.call(xAxis);
svg.append("g")
.attr('class', 'y axis')
.call(yAxis);
However, when I tried, I could only get a graph with all time on the xAxis shown as "00:00". What's going wrong here? Hope someone can help me out. Thanks!
Your example data is from different days, so what's happening here is that D3 is picking representative values (i.e. the boundaries between days) and making ticks for that. As your date format only shows hour and minute, 00:00 is all you get.
You have basically two options here. You could either change the date format to show days (which is what D3 intends), or you could set the tick values explicitly to whatever you want. For the first, you could use e.g. d3.time.format("%a"). For the second, see the documentation.
Hi You can use the tickFormat function on the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%H"));

D3 zoomable yAxis in hours

I am trying to figure out how to make a zoomable y axis that is in hours. I want the y axis to range from 7AM to 5PM. My x axis in days.
Currently, I have the y axis in hours but it only shows 12AM at the top of the y axis. I am unsure of where to get it to go from 7AM to 5PM. My code does zoom on both of the axis.
Any help would be appreciated :)
// Define the min and max date
var mindate = new Date(2013,0,20), // TODO: clip date
maxdate = new Date(2013,0,25);
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.time.scale()
.domain([mindate, maxdate])
.range([0, width]);
var y = d3.time.scale()
.domain([mindate, maxdate])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.days, 1)
.tickFormat(d3.time.format("%A : %d")); // d is for testing
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(d3.time.days, 12)
.tickFormat(d3.time.format("%I %p")); // For 12 hour time
var zoom = d3.behavior.zoom()
// .x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var svg = d3.select("body").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 + ")")
.call(zoom);
svg.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
I'm not 100% sure if this is what you're after, but I've interpreted your question as how to create a scale from 7am to 5pm on the same day with 1 hour steps. The first thing was to create a set of dates for the y-scale for the required time as in:
var ymindate = new Date(2013,0,20, 7), // TODO: clip date
ymaxdate = new Date(2013,0,20, 17);
The next step required only minor changes to your code. the ticks were set to d3.time.hours not days and the step was set to 1 hour, as shown below.
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(d3.time.hours, 1)
.tickFormat(d3.time.format("%I %p"));
If you want just 7am and 5pm to appear on multiple days you would have to create a custom set of ticks and use a time intervals
You would need to set the domain of the y scale accordingly. At the moment, your min and max dates are both full days, so you get only one value for the time. If you used for example
var mindate = new Date(2013,0,20, 7, 0, 0, 0),
maxdate = new Date(2013,0,25, 17, 0, 0, 0);
you should get the times you want on the y axis.

Categories

Resources