How do I change XTick format in NVD3? - javascript

I would like to change the XTick format of the small chart to also be a date. I have the following which is lifted from this example:
function chart(div)
{
var testdata = loadData();
nv.addGraph(function() {
var chart = nv.models.lineWithFocusChart();
chart.xAxis.tickFormat(function(d) {
var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
return d3.time.format('%x')(new Date(dx))
});
chart.yAxis
.tickFormat(d3.format(',.2f'));
chart.y2Axis
.tickFormat(d3.format(',.2f'));
d3.select(div + ' svg')
.datum(loadData())
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
}
But only the large chart's format changes to date.

There are two ways of fixing the ticks for the second x-axis.
The first way is by setting the tickFormat explicitly for the second axis as well. This design follows the traditional paradigm of setting one attribute at a time.
var xFormat = function(d) {
var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
return d3.time.format('%x')(new Date(dx));
};
chart.xAxis.tickFormat(xFormat);
chart.xAxis2.tickFormat(xFormat);
The second way, which would avoid code duplication, is setting both the axis together using a special function exposed by the chart API:
// This would set both the axis simultaneously
chart.xTickFormat(xFormat);
This function is present in the code (introduced here) for exactly this purpose. However, as the API is not very stable, it might be removed later.

Related

NVD3 chart shows tooltip for wrong data

I have a chart in NVD3 with a date on the X axis and a float on the Y axis.
It displays fine, but when I hover over the chart to make the tooltip pop up, it doesn't show it for the dataset I'm currently hovering over. Here's a GIF to make it more clear, hopefully:
This is the code I've used:
<script>
var data = function() {
return [
{
values: [
{x:"2018-09-08", y:19.98},{x:"2018-09-07", y:11.99},{x:"2018-09-06", y:9.98},{x:"2018-09-05", y:4.99},{x:"2018-09-03", y:9.98},{x:"2018-09-02", y:14.99}, ],
key: 'Turnover'
}
];
}
nv.addGraph(function() {
var chart = nv.models.lineChart()
.useInteractiveGuideline(true)
.xScale(d3.time.scale())
.x( function(d){return d3.time.format('%Y-%m-%d').parse(d.x);} );
;
chart.xAxis
.axisLabel('Date')
.tickFormat(function(d) {return d3.time.format("%Y-%m-%d")(new Date(d))});
;
chart.yAxis
.axisLabel('Sales')
.tickFormat(d3.format('.02f'))
;
chart.showLegend(false);
d3.select('#nvd3 svg')
.datum(data())
.transition().duration(500)
.call(chart)
;
nv.utils.windowResize(chart.update);
return chart;
});
</script>
Edit 1: When I do not use the .useInteractiveGuideline(true) function, it does work and the tooltip is presented on the correct set of data. However, I do want to use this function. So any help here?
Looking at the examples of the NVD3 site they work with a Linear Scale for time axis.
Converting the code to this too shows the requested behavior.
You have to set the tick positions yourself because the automatic ticks for a linear scale are not on dates
var data = function() {
return [
{
values: [
{x:"2018-09-02", y:14.99},
{x:"2018-09-03", y:9.98},
{x:"2018-09-05", y:5.99},
{x:"2018-09-06", y:9.98},
{x:"2018-09-07", y:11.99},
{x:"2018-09-08", y:19.98}
],
key: 'Turnover'
}
];
};
var formatDate = d3.time.format("%Y-%m-%d");
nv.addGraph(function () {
var chart = nv.models.lineChart()
.useInteractiveGuideline(true)
;
var mydata = data();
mydata[0].values.forEach(e => { e.x = Date.parse(e.x); });
chart.xAxis
.axisLabel('Date')
.tickFormat(function(d) {return formatDate(new Date(d))})
.tickValues(mydata[0].values.map( d => d.x ))
;
chart.yAxis
.axisLabel('Sales')
.tickFormat(d3.format('.02f'))
;
chart.showLegend(false);
d3.select('#nvd3 svg')
.datum(mydata)
.transition().duration(500)
.call(chart)
;
nv.utils.windowResize(chart.update);
return chart;
});

Creating newline in nvd3.js graph x-axis labels

so I've been trying to find a way to create new lines in the x-axis labels of my nvd3 graph but nothing seems to work so far. I have referred to these two questions: Newline in labels in d3 charts and nvd3 chart axis label but didn't find a sufficient answer because these are both relating to d3.js graphs. They both have answers relating to using tspan to create the new-line but doesn't seem to work for me no matter how much I play around with it. This is what I have now but it doesn't seem to be correct at all...any help would be appreciated!
nv.addGraph(function () {
var chart = nv.models.multiBarChart().stacked(false).showControls(false);
chart.x(function (d) { return d.x; });
chart.y(function (d) { return d.y; });
chart.yAxis
.axisLabel('Jobs')
//Too many bars and not enough room? Try staggering labels.
chart.staggerLabels(true);
chart.margin().left = 70;
//chart.showValues(true);
var tech_data = technicianReport();
console.log(tech_data[1] + " " + tech_data[2])
$("#date_range").text(tech_data[1] + " - " + tech_data[2]);
$("#tech_title").text("Technician-Advisor Actions");
d3.select('#tech_chart svg')
.datum(tech_data[0])
.transition().duration(500).call(chart);
var insertLinebreaks = function (d) {
var el = d3.select(this).text();
var words = d.description.split('\n');
el.text('');
for (var i = 0; i < words.length; i++) {
var tspan = el.append('tspan').text(words[i]);
if (i > 0)
tspan.attr('x', 0).attr('dy', '15');
}
};
svg = d3.select("tech_chart svg");
svg.selectAll('g.x.axis g text').each(insertLinebreaks);
nv.utils.windowResize(function () { chart.update() });
return chart;
});
Use .wrapLabels parameter from the latest nvd3 source (1.8.1-dev) The parameter wraps long x axis labels. Compare the two screenshots
So you'll come up with
chart.wrapLabels(true);

Custom tick size on axis (d3js)

I am creating a svg x-y-chart in d3.js. Is it possible to create ticks of different lengths depending on tickValue?
I have made my own tickFormat function myTickFormat and use that in .tickFormat([format]) and that works fine because [format] is expected to be a function. But it is not possible to do the same with .innerTickSize([size]), which expects a number.
E.g. if I want the tick at value 70 to be longer I want to do something like this:
var myTickSize = function(d) {
if (d === 70) { return 20;}
return 6;
};
But when I use myTickSize as argument to .innerTickSize():
var yScale = d3.scale.linear();
var yAxis = d3.svg.axis()
.scale(yScale).orient("left")
.innerTickSize(myTickSize);
I get an Error: Invalid value for attribute x2="NaN" error for each tick.
The tickSize function can only accept a number as argument, not a function, but there are other solutions.
The easiest approach? After the axis is drawn, select all the tick lines and resize them according to their data value. Just remember that you'll have to do this after every axis redraw, as well.
Example:
https://jsfiddle.net/zUj3E/1/
Key code:
d3.selectAll("g.y.axis g.tick line")
.attr("x2", function(d){
//d for the tick line is the value
//of that tick
//(a number between 0 and 1, in this case)
if ( (10*d)%2 ) //if it's an even multiple of 10%
return 10;
else
return 4;
});
Note that the tick marks at the max and min values are also drawn as part of the same <path> as the axis line, so shortening them doesn't have much effect. If you don't like that lack of control, declare the "outer" ticks to have zero length when you set up the axis. That turns off the corners of the path, but the outer ticks will still have lines that you can control the same as the other tick lines:
var axis = d3.svg.axis()
.tickSize(10,0)
Example: https://jsfiddle.net/zUj3E/2/
If that doesn't work, google for examples of major/minor tick patterns. Just make sure the example you're looking at uses d3 version 3: there were a few extra tick-related methods added in version 2 that are no longer supported. See this SO Q&A.
Variant on the answer that suits my requirements. Picked the values I just wanted tick marks for instead of ticks and value, added the "hide" class. But this can be used for any variation on the theme.
var gy = humiditySVG.append( "g" )
.attr( "class", "y axis" )
.attr( "transform", "translate(" + 154 + "," + 0 + ")" )
.call( yAxis );
humiditySVG.selectAll( "text" )
.attr( "class", function ( d ) {
if ( $.inArray(d, [0,50,100])==-1 ) {
return "hide";
}
return;
} );
humiditySVG.selectAll( "line" )
.attr( "x2", function ( d ) {
if ( $.inArray(d, [0,50,100])==-1 ) {
return 1;
} else {
return 3;
}
return;
} );

Display only whole values along y axis in d3.js when range is 0-1 or 0-2

I am using d3js to display a realtime representation of the views of a website. For this I use a stack layout and I update my dataset by JSON at the moment.
When there is only 1 or 2 views being displayed on the y axis, which is dynamic related to the amount of views in the graph, the axis labels are: 1 => 0, 0.2, 0.4, 0.6, 0.8, 1, the axis labels are: 2 => 0, 0.5, 1, 1.5, 2 This makes no sense for my dataset since it displays views of a page, and you can't have half a view.
I have a linear scale in d3js I base my y axis on
var y_inverted = d3.scale.linear().domain([0, 1]).rangeRound([0, height]);
According to the documentation of rangeRound() I should only get whole values out of this scale. For drawing my axis I use:
var y_axis = svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(0,0)")
.call(y_inverted.axis = d3.svg.axis()
.scale(y_inverted)
.orient("left")
.ticks(5));
Because it is a realtime application I update this every second by calling:
function update(){
y_inverted.domain([yStackMax, 0]);
y_axis.transition()
.duration(interval)
.ease("linear")
.call(y_inverted.axis);
}
yStackMax is calculated from a stacklayout, as far as I know the data used for the y values only contain integers.
var yStackMax = d3.max(layers, function(layer) {
return d3.max(layer, function(d) {
return d.y0 + d.y;
});
});
I have tried several things to get a proper value for my y axis.
d3.svg.axis()
.scale(y_inverted)
.orient("left")
.ticks(5).tickFormat(d3.format(",.0f"))
Got me the closest sofar, but it still displays 0, 0, 0, 1, 1, 1
Basically what I want is to only have 1 tick when yStackMax is 1, 2 ticks when it's 2, but it should also work if yStackMax is 12 or 1,000,000
Short answer: You can dynamically set the number of ticks. Set it to 1 to display only two tick labels:
var maxTicks = 5, minTicks = 1;
if (yStackMax < maxTicks) {
y_axis.ticks(minTicks)
}
else {
y_axis.ticks(maxTicks)
}
Long Answer (going a bit off topic):
While playing with your example I came up with a rather "complete solution" to all your formatting problems. Feel free to use it :)
var svg = d3.select("#svg")
var width = svg.attr("width")
var height = svg.attr("height")
var yStackMax = 100000
var interval = 500
var maxTicks = 5
var minTicks = 1
var y_inverted = d3.scale.linear().domain([0, 1]).rangeRound([0, height])
var defaultFormat = d3.format(",.0f")
var format = defaultFormat
var y_axis = d3.svg.axis()
.scale(y_inverted)
.orient("left")
.ticks(minTicks)
.tickFormat(doFormat)
var y_axis_root;
var decimals = 0;
function countDecimals(v){
var test = v, count = 0;
while(test > 10) {
test /= 10
count++;
}
return count;
}
function doFormat(d,i){
return format(d,i)
}
function init(){
y_axis_root = svg.append("g")
.attr("class", "y axis")
// I modified your example to move the axis to a visible part of the screen
.attr("transform", "translate(150,0)")
.call(y_axis)
}
// custom formatting functions:
function toTerra(d) { return (Math.round(d/10000000000)/100) + "T" }
function toGiga(d) { return (Math.round(d/10000000)/100) + "G" }
function toMega(d) { return (Math.round(d/10000)/100) + "M" }
function toKilo(d) { return (Math.round(d/10)/100) + "k" }
// the factor is just for testing and not needed if based on real world data
function update(factor){
factor = (factor) || 0.1;
yStackMax*=factor
decimals = countDecimals(yStackMax)
console.log("yStackMax decimals:",decimals, factor)
if (yStackMax < maxTicks) {
format = defaultFormat
y_axis.ticks(minTicks)
}
else {
y_axis.ticks(maxTicks)
if (decimals < 3 ) format = defaultFormat
else if(decimals < 6 ) format = toKilo
else if(decimals < 9 ) format = toMega
else if(decimals < 12) format = toGiga
else format = toTerra
}
y_inverted.domain([yStackMax, 0]);
y_axis_root.transition()
.duration(interval)
.ease("linear")
.call(y_axis);
}
init()
setTimeout(update, 200)
setTimeout(update, 400)
setTimeout(update, 600)
You can try it together with this html snippet:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js"></script>
</head>
<body>
<div><svg id="svg" width="200" height="300"></svg></div>
<script src="axis.js"></script>
<button id="button1" onclick="update(10)">+</button>
<button id="button2" onclick="update(0.1)">-</button>
</body>
</html>
I know it is a bit off topic but I usually like to provide running examples/solutions. Regard the additional formatting stuff as a bonus to the actual problem.
If you ask for a certain number of ticks (via axis.ticks() ) then d3 will try to give you that many ticks - but will try to use pretty values. It has nothing to do with your data.
Your solutions are to use tickFormat, as you did, to round all the values to integer values, only ask for one tick as Juve answered, or explicitly set the tick values using axis.tickValues([...]) which would be pretty easy used in conjunction with d3.range
rangeRound will not help in this case because it relates to the output range of the scale, which in this case is the pixel offset to plot at: between 0 and height.
Going off of Superboggly's answer, this is what worked for me. First I got the max (largest) number from the y domain using y.domain().slice(-1)[0] and then I built an array of tick values from that using d3.range()...
var y_max = y.domain().slice(-1)[0]
var yAxis = d3.svg.axis()
.scale(y)
.tickValues(d3.range(y_max+1))
.tickFormat(d3.format(",.0f"))
Or just let the ticks as they are and "hide" decimal numbers
d3.svg.axis()
.scale(y_inverted)
.orient("left")
.ticks(5).tickFormat(function(d) {
if (d % 1 == 0) {
return d3.format('.f')(d)
} else {
return ""
}
});
Here is the code:
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));

NVD3 not dealing with large values

I have a graph implemented in NVD3, and I'm having serious trouble with it. NVD3 seems unable to handle datasets which contain large values. The graph is located here: http://brad.kizer.com.ng/. The code for the graph is as so:
nv.addGraph(function() {
// Get maximum and minimum Y values
var minY = 2 >> 30,
maxY = 0;
data.forEach(function (d) {
d.values.forEach(function (s) {
minY = Math.min(minY, s.y);
maxY = Math.max(maxY, s.y);
});
});
var chart = nv.models.stackedArea()
.forceY([0, 20])
.height($(container).closest('.chart').height())
.width($(container).closest('.chart').width());
(Object.prototype.toString.call(data) === '[object Array]') || (data = [data]);
d3.select(container)
.attr('width', $(container).closest('.chart').width())
.attr('height', 250)
.datum(data)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
I will appreciate any help so much, as this has kept me scratching my head for days.
Solved my problem. The issue was that the data provided for the Y-axis was strings, which made supposedly number addition become string concatenation:
"123" + "902" + "384" + "382" == "123902384382"; // (instead of 1791)
What I did was walk through the data and convert the strings to numbers.

Categories

Resources