Angular nvd3 Line chart scrolling - angularjs

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

Related

Recreating collapsible force layout using d3 v4

I've been trying to create a Collapsible force layout using d3js v4, similar to this one: https://mbostock.github.io/d3/talk/20111116/force-collapsible.html
I've been able to create the layout itself. But not able to update it. Can anyone help?
Here's my js code:
var width = 960,
height = 600;
var root = {
"name": "server1900",
"children": [{
"name": "server913",
"_children": null,
"children": [{
"name": "server948"
}, {
"name": "server946"
}]
}, {
"name": "server912",
"_children": null,
"children": [{
"name": "server984"
}, {
"name": "server983"
}]
}, {
"name": "server911",
"_children": null,
"children": [{
"name": "server999",
"_children": null,
"children": [{
"name": "server992"
}]
}]
}]
};
root = d3.hierarchy(root);
var i = 0;
var transform = d3.zoomIdentity;;
var nodeSvg, linkSvg, simulation, nodeEnter, linkEnter ;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().scaleExtent([1 / 2, 8]).on("zoom", zoomed))
.append("g")
.attr("transform", "translate(40,0)");
function zoomed() {
svg.attr("transform", d3.event.transform);
}
simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.on("tick", ticked);
update();
function update() {
var nodes = flatten(root);
var links = root.links();
simulation
.nodes(nodes)
simulation.force("link")
.links(links);
linkSvg = svg.selectAll(".link")
.data(links, function(d) { return d.target.id; })
linkSvg.exit().remove();
linkSvg = linkSvg.enter()
.append("line")
.attr("class", "link");
nodeSvg = svg.selectAll(".node")
.data(nodes, function(d) { return d.id; })
nodeSvg.exit().remove();
nodeSvg = nodeSvg.enter()
.append("g")
.attr("class", "node")
.on("click", click)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
nodeSvg.append("circle")
.attr("r", 4 )
.append("title")
.text(function(d) { return d.data.name; })
nodeSvg.append("text")
.attr("dy", 3)
.attr("x", function(d) { return d.children ? -8 : 8; })
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text(function(d) { return d.data.name; });
}
function ticked() {
linkSvg
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
nodeSvg
.attr("transform", function(d) { return "translate(" + d.x + ", " + d.y + ")"; });
}
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
update();
simulation.restart();
} else {
d.children = d._children;
d._children = null;
update();
simulation.restart();
}
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart()
simulation.fix(d);
}
function dragged(d) {
simulation.fix(d, d3.event.x, d3.event.y);
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
simulation.unfix(d);
}
function flatten (root) {
// hierarchical data to flat data for force layout
var nodes = [];
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (!node.id) node.id = ++i;
else ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
line {
stroke: #666;
}
.node {
pointer-events: all;
}
circle {
stroke: none;
stroke-width: 40px;
}
.node text {
font: 8px sans-serif;
}
<script src="https://d3js.org/d3.v4.0.0-alpha.50.min.js"></script>
Here's my fiddle. https://jsfiddle.net/t4vzg650/4/
Thanks
I forgot to merge old nodes after enter().
link = svg.selectAll(".link").data(links, function(d) { return d.target.id; })
var linkEnter = link.enter().append("line").attr("class", "link");
link = linkEnter.merge(link);
Thanks to Mike Bostock for helping me with this problem. I thought there was an issue with d3 v4, turns out I didn't read changes fully :|
Refer this for more info: https://github.com/d3/d3-force/issues/37
Fixed fiddle: https://jsfiddle.net/t4vzg650/6/

nvd3 pie chart when no data and for value zero

I have created a pie chart using nvd3.
Here is my code :
<nvd3-pie-chart
data="examplePieData"
id="exampleId"
showLabels="true"
labelType="value"
x="xPieFunction()"
y="yPieFunction()"
donut="true"
donutRatio=".5"
tooltips="true"
noData="Data aint here"
tooltipcontent="toolTipContentFunction()"
color="pieColorFunction()"
donutLabelsOutside="false">
<svg height="200" style="margin-left: -121px; margin-top: -49px;"></svg>
</nvd3-pie-chart>
and
$scope.examplePieData = [
{
key: "First",
y: 5
},
{
key: "Second",
y: 3
},
{
key: "Third",
y: 1
}
];
$scope.toolTipContentFunction = function(){
return function(key, x, y, e, graph) {
return '<p>' + key +" "+ y.value + '</p>'
}
}
$scope.xPieFunction = function(){
return function(d) {
return d.key;
};
}
$scope.yPieFunction = function(){
return function(d) {
return d.y;
};
}
var pieColorArray = [ '#5EA9DD','#e76060', '#008000'];
$scope.pieColorFunction = function() {
return function(d, i) {
return pieColorArray[i];
};
}
Here I want to display a message when there is no data. I have tried with noDate = "Message" but it is not working. And I want to show pic chart even for y value is zero (y :0). Finally, how to adjust tooltip distance and same color for the tooltip when mouseover on the perticular field in pie chart. Help me. Thank you.
For no data, try with chart.noData() function. For me it is perfectly working,
HTML:
<div id="chart">
<svg></svg>
</div>
Javascript:
var h = 300;
var r = h/2;
var data = [];
var colors = [
'rgb(178, 55, 56)',
'rgb(213, 69, 70)',
'rgb(230, 125, 126)',
'rgb(239, 183, 182)'
];
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.color(colors)
.showLabels(true)
.labelType("percent");
chart.noData("No data");
d3.select("#chart svg")
.datum(data)
.transition().duration(1200)
.call(chart)
;
return chart;
});

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.

nvD3, line chart, D3, angular

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

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