nvD3, line chart, D3, angular - angularjs

Can any one help why my line chart is not plotting correctly? I have put my code with data at : http://jsfiddle.net/madasuk/U9KH5/4/
can any one help to plot it correctly? lines in the graph are jumbled up and tool tip is also not appearing?
function addLineChart(){
var chart;
nv.addGraph(function() {
chart = nv.models.lineChart()
.options({
margin: {left: 100, bottom: 100},
// x: function(d,i) { return i},
x : (function(d,i) {
return new Date(d.x);
}),
showXAxis: true,
showYAxis: true,
transitionDuration: 250
})
;
// chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
chart.xAxis
.axisLabel("Time (s)")
// .tickFormat(d3.format(',.1f'));
.tickFormat(function(d) {
return d3.time.format('%m/%d/%y')(new Date(d))
});
chart.yAxis
.axisLabel('Voltage (v)')
.tickFormat(d3.format(',.2f'))
// .tickFormat(d3.format(',g'));
;
d3.select('#chart1 svg')
.datum(cumulativeMSIData())
.call(chart);
//TODO: Figure out a good way to do this automatically
nv.utils.windowResize(chart.update);
//nv.utils.windowResize(function() { d3.select('#chart1 svg').call(chart) });
chart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e)); });
return chart;
});
}

Related

custom legend hide() does not remove data labels

I am building a project using React with a doughnut and bar chart. Working with Chart.js 3.xx.
I am trying to make my custom legend functional. I want to make data fractions disappear when the user clicks my legend items - like in the native legend, and optimally also remove the data and make the chart present it's updated data after removal.
I also use data labels to present percentage of the data on the fractions.
import ChartDataLabels from 'chartjs-plugin-datalabels';
I came across this topic: ChartJS - Show/hide data individually instead of entire dataset on bar/line charts
and used this suggested code there:
function chartOnClick(evt) {
let chart = evt.chart
const points = chart.getElementsAtEventForMode(evt, 'nearest', {}, true);
if (points.length) {
const firstPoint = points[0];
//var label = myChart.data.labels[firstPoint.index];
//var value = myChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
let datasetIndex = firstPoint.datasetIndex, index = firstPoint.index;
if (firstPoint.element.hidden != true) {
chart.hide(datasetIndex, index);
} else {
chart.show(datasetIndex, index);
}
}
}
options: { // chart options
onClick: chartOnClick
}
It almost works, but the hide() method doesn't remove the fraction's percentage data label when activated, whereas when clicking the native legend it does remove it entirely.
I tried looking in the plugin's docs but didn't manage to find how to remove a single label.
How can I achieve what I am looking for?
EDIT:
Options Object:
export const doughnutOptsObj = {
onClick: chartOnClick,
responsive: true,
maintainAspectRatio: false,
layout: { padding: { top: 16, bottom: 16 } },
hoverOffset: 32,
plugins: {
legend: {
display: true,
position: 'bottom',
},
datalabels: {
formatter: (value, dnct1) => {
let sum = 0;
let dataArr = dnct1.chart.data.datasets[0].data;
dataArr.map((data) => {
sum += Number(data);
});
let percentage = ((value * 100) / sum).toFixed() + '%';
return percentage;
},
color: ['#fbfcfd'],
font: { weight: 'bold' },
// display: false, <-- this works and makes all of the data labels disappear
},
},
};
It seems that the onClick function is working properly.
I have tried the attached code, leveraging on toggleDataVisibility API, and it's working as requested (codepen: https://codepen.io/stockinail/pen/abKNJqJ):
function chartOnClick(evt) {
let chart = evt.chart
const points = chart.getElementsAtEventForMode(evt, 'nearest', {}, true);
if (points.length) {
const firstPoint = points[0];
chart.toggleDataVisibility(firstPoint.index);
chart.update();
}
}

Angular nvd3 Line chart scrolling

How to do scrolling along the x axis with Angular nvd3?
I find this http://blog.scottlogic.com/2014/09/19/interactive.html and
http://bl.ocks.org/stepheneb/1182434
but it is too difficult
It doesn't work
xAxis: {
scale: d3.scale.linear()
.range([0, innerwidth])
.domain([d3.min(d3, function (d) {
return d3.min(d.x);
}),
d3.max(d3, function (d) {
return d3.max(d.x);
})]),
tickFormat: function (d) {
return d3.format(',f')(d);
}
}
Or make in without time
xAxis: {
scale: d3.time.scale().domain([beginDate, endDate]), // <-- explicitly set time scale
tickFormat: function(d) {
return $filter('date')(d, 'mediumDate');
}

How to customize tooltip for forceDirectedGraph in angular nvd3

I am using the force directed graph in angular nv3d. I would like to customize the text color on the nodes as well as modify the tool tip. Ive also been trying to figure out how to force the nodes to be more sparse. Here is my chart object:
chart: {
type: 'forceDirectedGraph',
height: 450,
color: function(d) {
return color(d.Name);
},
tooltipContent: function (key) {
return '<h3>' + key + '</h3>';
},
margin: {top: 20, right: 20, bottom: 20, left: 20},
nodeExtras: function(node) {
node && node
.append('text')
.attr('dx', 15)
.attr('dy', '.35em')
.text(function(d) {
return d.Name;
})
.style('font-size', '25px');
},
},
};
As you can see, I tried adding the tooltipContent property to the chart object to no avail. Any help would be greatly appreciated, thanks!
To customize the tool tip do the following
chart: {
type: 'forceDirectedGraph',
... /* All properties */
height : 400,
tooltip : {
contentGenerator : function (obj) { return "<div> **custom formating** </div>"}
}
}

angularjs-nvd3-directives line chart ticks doesn't work

I work with cmaurer nvd3 directives with angularjs and you can see it here
I want to change the x-axis ticks count to 3 (start, middle, end dates), but nvd3 ticks properties(xaxisticks, xaxistickvalues) don't work.
I even tried to use unix timestamp, but no success.
Have any thoughts?
<nvd3-line-chart
...
xAxisTickFormat="xAxisTickFormatFunction()"
yAxisTickFormat="yAxisTickFormatFunction()"
xaxistickvalues="xAxisTickValuesFunction()" // not work
xaxisticks="3" // not work
showXAxis="true"
showYAxis="true"
interactive="true"
...
forcey="[]"
>
<svg></svg>
</nvd3-line-chart>
Not a perfect solution, but was a quick change that removes duplication for the most part. Add a cache of the ticks as they are created, and since they are create in order, can eliminate sequential dupes.
controller: function($scope) {
var vm = this;
vm.xAxisTick = ""; // <- cache the x-axis ticks here...
vm.x2AxisTick = ""; // <- cache the x2-axis ticks here...
vm.options = {
chart: {
type: 'lineWithFocusChart',
xAxis: {
scale: d3.time.scale(),
tickFormat: function(d) {
var tick = moment.unix(d).format('h:mm a');
// compare tick versus the last one,
// return empty string if match
if (vm.xAxisTick === tick) {
return "";
}
// update our latest tick, and pass along to the chart
vm.xAxisTick = tick;
return tick;
},
rotateLabels: 30,
showMaxMin: false
},
x2Axis: {
scale: d3.time.scale(),
tickFormat: function(d) {
var tick = moment.unix(d).format('h:mm a');
// compare tick versus the last one,
// return empty string if match
if (vm.x2AxisTick === tick) {
return "";
}
// update our latest tick, and pass along to the chart
vm.x2AxisTick = tick;
return tick;
},
rotateLabels: 30,
showMaxMin: false
},
yAxis: {
axisLabel: 'Why',
axisLabelDistance: 30,
rotateYLabel: false
}
}
};
It seems all line charts in nvd3 have the ticks hardcoded, so any ticks setting gets ignored:
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight, 0);
See here: https://github.com/novus/nvd3/issues/70. Sadly it seems to get it working one needs to fork the library, or wait until version 2.0 is released, hopefully solving this among other bugs.

Can not export renderer text using highcharts/highstock when click range selector

I have a question related the chart export.
Please see Jsfiddle here
I added a text label using chart.renderer.text on the Yaxis for the latest value of series.
If I directly click button "Export Image". There is no problem, the label can be displayed. I'm using the following way to export image. draw_labels() is a function to draw yaxis label.
$("#b").click(function () {
chart.exportChart(null, {
chart: {
backgroundColor: '#FFFFFF',
width: 972,
height: 480,
events: {
load: function () {
draw_labels(this);
}
}
}
});
});
The problem is after I clicked range selector or change Xaxis range. When I try to export the
chart to image, there is no labels are drawn. The following is the complete code.
The following is the complete code:
$(function () {
var chart;
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
events: {
load: function () {
draw_labels(this);
$("#b").click(function () {
chart.exportChart(null, {
chart: {
backgroundColor: '#FFFFFF',
width: 972,
height: 480,
events: {
load: function () {
draw_labels(this);
}
}
}
});
});
}
}
},
series: [{
name: 'AAPL',
id: 'test',
data: data,
tooltip: {
valueDecimals: 2
}
}],
navigator: {
enabled: false
},
yAxis: {
tickWidth: 0,
id: 'value_axis',
type: 'linear',
gridLineColor: '#EEE',
lineColor: '#D0CDC9',
lineWidth: 0,
minorTickInterval: null,
opposite: true,
offset: 0
},
xAxis: {
events: {
afterSetExtremes: function (e) {
console.log('test');
$('[id="test_text"]').remove();
draw_labels(chart);
}
}
}
});
});
function draw_labels(chart) {
$(chart.series).each(function (i, serie) {
var s_id = serie.options.id;
var temp_id = s_id;
var point = serie.points[serie.points.length - 1];
if (point) {
var pre, post;
if (point.y) {
var last_value_dis = (point.y).toFixed(1);
yaxis_name = 'value_axis';
//Get Yaxis position
var y_axis = chart.get(yaxis_name);
offsite_yaxis = 0;
element_text = chart.renderer.text(
//the text to render
'<span style="font-size:10px;font-weight:bold;color:' + serie.color + ';">' + last_value_dis + '</span>',
//the 'x' position
y_axis.width + y_axis.offset,
//the 'y' position
chart.plotTop + point.plotY + 3).attr({
id: temp_id + '_text',
zIndex: 999
}).add();
}
}
});
}
});
Here, I have fixed it for you. Here is a saved image:
Following changes have been done:
Added a redraw event to your exportchart
redraw: function () {
$("#test_text").remove() ;
draw_labels(this);
}
Changed this line in afterSetExtremes
$('[id="test_text"]').remove();
to
$("#test_text").remove() ;
Earlier one was not working as expected, so I had to change it.
Problem with disappearing text is related with id, when I removed it, label appears. But then I came across second issue, wrong y position. So i declare global variable, then when you call your function, set position of label, and use in chart exporting this variable. As a result label is exported correct.
http://jsfiddle.net/UGbpJ/11/

Resources