NVD3 - x axis labels fail - javascript

I am trying to customize the x-axis label for a line plot with NV D3 but all I get is the iteration from 0 - N
Here's my code
for(var i = 0;i< numberBins;i++){
valuesForD3.push({x:parseFloat(histogramObject['min']) + parseFloat(i * histogramObject['binWidth']),
y:histogramObject['values'][i]
});
}
chart = nv.models.lineChart()
.options({
margin: {left: 50, bottom: 40},
x: function(d,i) { return i},
showXAxis: true,
showYAxis: true,
transitionDuration: 100
});
d3.select('#chart1 svg')
.datum([{values:valuesForD3,key:'Score values',color:'#2222ff'}])
.call(chart);

Looking at their examples (where's the documentation!), you can customize the ticks like:
chart.xAxis
.tickFormat(function(d) {
return d.someTickLabel;
});
Here's a quick example.

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;
});

How to add JSON data to nvd3 charts

I am new to Javascript and couldn't find error in my code.
I am using NVD3 charts here. It is a time series based chart with date and closing prices of a particular stock. Data ranges from 2005 till now.
Here is the code
var data= JSON.parse("Data.JSON")
nv.addGraph(function() {
var chart = nv.models.lineChart()
.margin({top: 70, right: 70, bottom: 70, left: 70})
.useInteractiveGuideline(true)
.transitionDuration(100)
.showYAxis(true)
.showXAxis(true)
;
//Chart x-axis settings
chart.xAxis
.axisLabel('date')
.tickFormat(function(d) {return new Date((data.Date - (25567 + 1))*86400*1000);
chart.yAxis //Chart y-axis settings
.axisLabel('close')
.tickFormat(d3.scale.linear(data.Close));
d3.select('#Charts svg') //Selecting the <svg> element where i want to render the chart in.
.datum(data) //Populating the <svg> element with chart data...
.call(chart); //Finally, rendering the chart!
//Update the chart when window resizes.
})
;
//Data
{
"Date": [13089, 13094, 13095, 13096, 13097, 13098, 13101, 13103, 13104, 13105, 13108, 13109, 13110]
"Close": [ 2419.1, 2461.6, 2492.7, 2489.1, 2500.7, 2548.7, 2558.7, 2582.8, 2603.9, 2620.1, 2602.5, 2572.8]
}
The number of array elements in "Close" are less compared to "Date".
Here is a possible solution that you might be looking for:
nv.addGraph(function () {
var chart = nv.models.lineChart();
chart.xAxis.axisLabel('date')
.tickFormat(d3.format(''));
chart.yAxis.axisLabel('close')
.tickFormat(d3.format(''));
d3.select('#dateChart')
.datum(chartData())
.transition().duration(500)
.call(chart);
nv.utils.windowResize(function () {
d3.select('#dateChart').call(chart)
});
return chart;
});
function chartData() {
var myData = {
"Date": [13089, 13094, 13095, 13096, 13097, 13098, 13101, 13103, 13104, 13105, 13108, 13109, 13110],
"Close": [2419.1, 2461.6, 2492.7, 2489.1, 2500.7, 2548.7, 2558.7, 2582.8, 2603.9, 2620.1, 2602.5, 2572.8, 2588.8]
//The number of array elements in Close were less compared to Date. Hence added 2588.8 as the last element
};
var result = [];
for (var i = 0; i < myData.Date.length; i++) {
result.push({
x: myData.Date[i],
y: myData.Close[i]
});
}
return [{
values: result,
key: 'Date Chart',
color: '#ff7f0e'
}];
}
JS Fiddle: https://jsfiddle.net/m7oaxjue/3/

change axis labels in dc.js

how i can change the date format in my chart axis?
i want it formatted like this - "11/08"
var hourDim = ndx.dimension(function(d) { return d["CR_DATE"]; })
var HourCalc = hourDim.group().reduceSum(function(d) {return d["AMOUNT"];})
width(600)
.height(160)
.margins({top: 10, right: 50, bottom: 30, left: 50})
.dimension(hourDim)
.group( HourCalc)
.transitionDuration(500)
.x(d3.time.scale().domain([minDate, maxDate]))
.elasticY(true)
.xAxisLabel("DATE").xUnits(d3.time.days)
.yAxis().tickFormat(function(v) {return NumberFormat(v) ;})

Only end tick mark is showing on dc.js bubble chart

I have the following bubble chart coded with dc.js which is built upon d3.js.
All is good, but for some reason I cannot see the tick marks. When I inspect the DOM I can see that they are present:
<line y2="6" x2="0"></line>
And I have applied CSS styles to them, but still they do not show!
#referrals-bubble-chart .axis .tick line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
I even added a stroke-width of 2px and still nothing shows! I know I'm targeting the right elements in my CSS because when I give it a stroke width of 10px and hover (Chrome Inspector), I see that the line is now 10px wide.
Why is this happening? Chart Code is below:
// define the referrals bubble chart attributes
referralsChart
.width(700)
.height(400)
.transitionDuration(1500) // (optional) define chart transition duration, :default = 750
.margins({top: 10, right: 50, bottom: 40, left: 50})
.dimension(diagnosisDimension)
//Bubble chart expect the groups are reduced to multiple values which would then be used
//to generate x, y, and radius for each key (bubble) in the group
.group(diagnosisDimensionGroup)
.colors(colorbrewer.RdYlGn[9]) // (optional) define color function or array for bubbles
.colorDomain([0, 100]) //(optional) define color domain to match your data domain if you want to bind data or color
.colorAccessor(function (d) {
// color - mapped to internal scale
return d.value.cost % 100;
})
.keyAccessor(function (p) {
// x-axis
return p.value.avgrtt / p.value.referrals;
})
.valueAccessor(function (p) {
// y-axis
return p.value.cost / 1000;
})
.radiusValueAccessor(function (p) {
// radius size - default is [0, 100]
return p.value.referrals;
})
.maxBubbleRelativeSize(0.1)
// .x(d3.scale.linear().domain([0, 5000]))
.x(d3.scale.linear().domain([1, 15]))
.y(d3.scale.linear().domain([1000, 10000]))
.r(d3.scale.linear().domain([0, 4000]))
//##### Elastic Scaling
//`.elasticX` and `.elasticX` determine whether the chart should rescale each axis to fit data.
//The `.yAxisPadding` and `.xAxisPadding` add padding to data above and below their max values in the same unit domains as the Accessors.
.elasticY(true)
.elasticX(false)
.yAxisPadding(200)
.xAxisLabel('Average Waiting Time - (weeks)') // (optional) render an axis label below the x axis
.yAxisLabel('Cost - (£1K)') // (optional) render a vertical axis lable left of the y axis
//#### Labels and Titles
//Labels are displaed on the chart for each bubble. Titles displayed on mouseover.
.renderLabel(true) // (optional) whether chart should render labels, :default = true
.label(function (p) {
return p.key;
})
.renderTitle(true) // (optional) whether chart should render titles, :default = false
.title(function (p) {
return [p.key,
"Referrals: " + p.value.referrals,
"Cost: £" + p.value.cost,
"RTT: " + p.value.avgrtt / p.value.referrals + " weeks"]
.join("\n");
})
//#### Customize Axis
//Set a custom tick format. Note `.yAxis()` returns an axis object, so any additional method chaining applies to the axis, not the chart.
.yAxis().tickFormat(function (v) {
return v;
});
As mentioned in the comments, it's hard to help you without a complete example, but this works for me. Since I don't have your data I made my own very simple data and adjusted a few things on my bubble chart.
var data = [];
for (var i = 1; i < 10; i++) {
data.push({
val: i
});
}
var ndx = crossfilter(data);
var dim = ndx.dimension(function(d) {
return d.val;
});
var group = dim.group().reduceSum(function(d) {
return d.val;
});
bubbleChart = dc.bubbleChart("#bubbleChart");
bubbleChart
.width(700)
.height(400)
.transitionDuration(1500)
.margins({top: 10, right: 50, bottom: 40, left: 50})
.dimension(dim)
.group(group)
.keyAccessor(function (p) {
return p.value;
})
.valueAccessor(function (p) {
return p.value;
})
.maxBubbleRelativeSize(0.1)
.x(d3.scale.linear().domain([-1, 10]))
.y(d3.scale.linear().domain([0, 10]))
.radiusValueAccessor(function (p) {
return p.value;
})
.r(d3.scale.linear().domain([0, 100]))
.elasticY(true)
.elasticX(false)
.yAxisPadding(200)
.xAxisLabel('Average Waiting Time - (weeks)')
.yAxisLabel('Cost - (£1K)')
.renderLabel(true)
.label(function (p) {
return p.key;
})
.renderTitle(true)
.title(function (p) {
return "This is the title";
})
.yAxis().tickFormat(function (v) {
return v;
});
dc.renderAll();

NVD3 chart: Plot toggle with muiltiChart / multiple yScales causes axis to disappear, but not the plot

I'm trying to get two lines to use two different scales.
When I try to toggle a plot, the grid lines disappear, instead of the plot.
Can you figure out what I'm doing wrong?
http://jsfiddle.net/3ZP3S/
var dataset1 = {
values : [],
key : "Math.cos",
type: "line",
color: '#2ca02c',
yAxis: 1
};
var dataset2 = {
values : [],
key : "sin",
type: "line",
color : "#ff7f0e",
yAxis: 2
};
for (var i = -3.14; i < 3.1415; i+= .01){
dataset1.values.push( { x: i , y : Math.cos(i) });
dataset2.values.push( { x: i , y : Math.sin(i) * 3 });
}
var data = [dataset1, dataset2];
nv.addGraph( function() {
var chart = nv.models.multiChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.color(d3.scale.category10().range());
chart.xAxis
.tickFormat(d3.format(',.2f'));
chart.yAxis1
.tickFormat(d3.format(',.1f'));
chart.yAxis2
.tickFormat(d3.format(',.1f'));
d3.select('#chart svg')
.datum(data)
.transition().duration(500).call(chart);
return chart;
});
This was a bug with nvd3. I tried several "previous" versions of nvd3, and d3, and this always occurred.
We also decided to drop nvd3 and switch to C3.js, which seems to be "much" more mature in terms of stability...

Categories

Resources