I have a d3 graph plotted which denotes some data over the last 30 days. So my x axis is a linear scale because I am not using dates(instead using number of days). Now to show the x axis , I use code some thing like
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.outerTickSize(15)
.ticks(4)
This gives me four ticks like the following:
Now my problem is that instead of these ticks(numbers), I want to show tick labels from the following array :
var xArray = ['one month ago', '3 weeks ago', '2 weeks ago', '1 week ago', 'today'];
Any idea how to do this ? (I guess I cannot use ordinal scale because the graph being plotted uses linear scale, I cant mess with that)
This should have occured to me earlier that I could use a different(ordinal) scale just for the axis purpose. Anyway might help someone with a same doubt
var xScaleForAxis = d3.scale.ordinal()
.domain(xArray)
.rangePoints([0, WIDTH]);
Now I can use this scale something like following to get the desired result.
var xAxis = d3.svg.axis()
.scale(xScaleForAxis)
.orient("bottom")
.innerTickSize(-HEIGHT)
.ticks(4)
This gives me the following desired result.
Related
I am trying to plot stock data with a d3 line Chart. It has ugly spaces for weekends because there is no data available for weekends. What is the best way to make the X axis chart only the dates that I have data for?
const x = d3
.scaleTime()
.domain(d3.extent(data, (d) => d.datetime))
.range([0, width]);
d3 newbie experiencing a heavy learning curve at the moment.
For anyone who may have the same question:
const x = d3
.scaleBand()
.domain(data.map((d) => d.datetime))
.range([0, width]);
Band scale graphs only the dates you have data for.
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
I'm having an issue with the D3.js library. I'm trying to plot out chromosomal data in a graph where the x-axis represents the different chromosomes. This is easy enough done for barcharts etc.
However, I would like to plot linear data based on the chromosomal position. The size of the interval between the ticks should also correlate to the size of the chromosome.
My question is, which scale should I use? I don't think a linear scale would fit this purpose. I've read something about threshold scales, but I don't know if this is the best option. Does anyone have a better idea?
Thanks!
M
tl;dr: I need an x-axis with variable intervals between the ticks, based on linear data, how do I go about it?
EDIT: Image with example
Found the answer!
I just needed to use a linear scale with custom ticks. This can be set by using the tick formatting options.
//set axis
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(chrInfo.length)
.tickValues(d3.set(chrInfo.map(function(d) {return d.end;})).values())
.tickFormat(function(d){return d.chr;})
.tickSize(-(height), 0, 0);
I have a chart where the x Axis represents calendarweeks. Because of the change of the year my chart is now not right sorted. So the calendarweek 1 from 2015 is now before the calendarweeks from 2014.
I know that I have to change something in my data. I thought of adding the year before the calendarweek like 151, 152, 1450, 1451, 1452 and so on.
I tried this and it works. But it is not really readable then for the customer. So I thought I could just parse the calendarweek number to 1, 2, 50, 51 and 52 again and send it to the xAxis variable.
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(sliceKeys)
.orient("bottom");
But then it happens that the ticks won't match with the bars and don't appear. But the bars are right sorted now. Does anybody has an idea how this could be done?
As per Lars's recommendation in the comments above, you can use .tickFormat() to transform the value with the year into a value without the year.
Here's a modified fiddle. I disabled your slicing of the keys (but did it in a lazy way by just commenting out the slicing part without removing the entire loop, even though it's no longer necessary).
Then, the only thing that was needed is the .tickFormat() bit that strips the year out of the full value:
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(sliceKeys)
.tickFormat(function(yearAndWeek) {
return String(yearAndWeek).slice(2);
})
.orient("bottom");
I'm using D3.js to generate a graph with response times over time. Previously I was using Google Charts but it was too heavy. D3 is nice and lightweight, but there's something I can't manage to do that I could do with Google Charts.
The problem is that those graphs sometimes span over one week, sometimes over one day, sometimes over one hour. For each case I have to manually modify how the ticks in the X axis appear. I'm doing it by comparing the first and the last values for the X axis, and checking how much time there's between them, like this:
if (dateDif < 25) { // daily
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(d3.time.format('%H:%M'))
.ticks(d3.time.hours, 3)
.orient("bottom");
}
else if (dateDif <= 170) { // ~ weekly
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(d3.time.format('%d/%m %H:%M'))
.ticks(d3.time.hours, 24)
.orient("bottom");
} else { // more than weekly
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(d3.time.format('%d/%m %H:%M'))
.ticks(d3.time.hours, 96)
.orient("bottom");
}
But that it's not good, at all, specially when there are just a few values in the chart (they're generated every minute), then no ticks appear (because it falls in the first case, and there are no enough values to span 3 hours).
Do you know of any plugin or method that automagically adapts the X axis for this kind of situations?
d3.svg.axis() is fairly good at handling this type of behavior by default - try removing .tickFormat(...) from your axis, and setting .ticks(n) where n is the desired number of ticks you want on the axis at any scale zoom level - this might be sufficient for what you desire.
Here are a couple of related examples:
http://bl.ocks.org/mbostock/2983699
http://bl.ocks.org/mbostock/1166403
You could define a function to get the tickFormat based on the dateDif, so you wouldn't need to have such a large if-else block.
function getFormat() {
if (dateDif < 25) {
return d3.time.format('%H:%M');
} else {
return d3.time.format('%d/%m %H:%M');
}
}
Then you can set .ticks() to a number. In the output, roughly that many ticks will be shown. d3 chooses a number of ticks that is close to your requested value, but also makes a few decisions to try to give optimal output.
// approximately 10 ticks will be displayed
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(getFormat())
.ticks(10)
.orient("bottom");
If you use this method, you lose a little control over the exact number of ticks that will be shown, but you are guaranteed to have ticks displayed, and if you choose a sensible number for your ticks value, the output will probably be satisfactory.
Here's a fiddle using this technique with some contrived data.