Change title dynamically in ndv3 pie chart - d3.js

I am building a pie-chart with nvd3 and cannot figure out how to make the title dynamic or at least to run a callback when a user hovers over a slice of the pie.
This is the relevant part of my code:
nv.addGraph(function () {
let chart : any = nv.models.pieChart()
.x(function (d : any) {
return d.label;
})
.y(function (d : any) {
return d.value;
})
.showLabels(false)
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.6) //Configure how big you want the donut hole size to be.
.showLegend(false)
.color(function (d : any) {
return d.data.color;
})
.width(300)
.height(300)
.title("Hello");
//.on("mouseover", function(d: any) { console.log(d); });
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
The chart works exactly as intended otherwise.
This is a codepen with the chart. For some reason the color does not work but in my own site it works.

You can use dispatch method of NVD3 library for event subscribing and of course, you can use any native d3 methods, for example d3.select. Just add this to your code:
chart.pie.dispatch.on('elementMouseover', function(e) {
d3.select('.nv-pie-title').text(e.label);
});
chart.pie.dispatch.on('elementMouseout', function(e) {
d3.select('.nv-pie-title').text("Hello");
});
Check working demo in the hidden snippet below:
nv.addGraph(function() {
let chart = nv.models.pieChart()
.x(function(d) {
return d.label;
})
.y(function(d) {
return d.value;
})
.showLabels(false)
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.6) //Configure how big you want the donut hole size to be.
.showLegend(false)
.color(function(d) {
return d.data.color;
})
.width(300)
.height(300)
.title("Hello");
//.on("mouseover", function(d: any) { console.log(d); });
chart.pie.dispatch.on('elementMouseover', function(e) {
d3.select('.nv-pie-title').text(e.label);
});
chart.pie.dispatch.on('elementMouseout', function(e) {
d3.select('.nv-pie-title').text("Hello");
});
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
function exampleData() {
return [{
label: "timeout",
value: "14.2",
data: {
"color": "#f00"
}
}, {
label: "uncontacted",
value: "78.8",
data: {
"color": "#999999"
}
}, {
label: "refused",
value: "6.9",
data: {
"color": "#FFFFFF"
}
}];
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.min.js"></script>
<div id="chart">
<svg style="height: 300px; margin: -20px 0;"></svg>
</div>

Related

NVD3 - show tick lines only on axes

TLDR: I have an NVD3 graph that shows tick lines all across the axis, but I would like to change it so it only displays on the axis lines if possible.
Here is a live example:
var app = angular.module('plunker', ['nvd3']);
app.controller('MainCtrl', function($scope) {
$scope.options = {
chart: {
type: 'lineChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 80,
left: 55
},
x: function(d){ return d.x; },
y: function(d){ return d.y; },
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Timeline',
tickFormat: function(d) {
return d3.time.format('%B %d')(new Date(d))
},
ticks: 6,
showMaxMin: false
},
yAxis: {
axisLabel: 'Molecular density (kg/m^3)',
tickFormat: function(d){
return d3.format('.02f')(d);
},
axisLabelDistance: -10,
showMaxMin: false
}
}
};
$scope.data = [{"key":"K7 molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":9},{"x":1435881600000,"y":8},{"x":1435968000000,"y":8},{"x":1436054400000,"y":9},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":8},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":7},{"x":1436659200000,"y":8}],"area":true,"color":"#0CB3EE"},{"key":"N41 type C molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":7},{"x":1435881600000,"y":8},{"x":1435968000000,"y":9},{"x":1436054400000,"y":7},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":9},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":9},{"x":1436659200000,"y":8}],"area":true,"color":"#383838"}];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>Angular-nvD3 Line Chart</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css"/>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.js"></script>
<script src="https://rawgit.com/krispo/angular-nvd3/v1.0.1/dist/angular-nvd3.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<nvd3 options="options" data="data" class="with-3d-shadow with-transitions"></nvd3>
</body>
</html>
Is there any way I could make the tick lines appear just on the axes line only? To make it clear, this is what it looks like:
I used a different library to generate the following plot, and I would like the tick lines to appear just on the axis lines like this example instead:
It appears that there is no real way to do this with NVD3 as it does not provide a way to show tick marks on the axis. However, we could add our own tick marks by fetching the chart SVG and then modifying it.
I've attached an example that adds tick marks to X-Axis, and it is basically slightly modified based on this jsfiddle here: http://jsfiddle.net/3r88bgjw
var data;
data = [{
values: [],
}, ];
var i, x;
var prevVal = 3000;
var tickCount = 2000;
for (i = 0; i < tickCount; i++) {
x = 1425096000 + i * 10 * 60; // data points every ten minutes
if (Math.random() < 0.8) { // add some gaps
prevVal += (Math.random() - 0.5) * 500;
if (prevVal <= 0) {
prevVal = Math.random() * 100;
}
data[0].values.push({
x: x * 1000,
y: prevVal
});
}
}
var chart;
nv.addGraph(function() {
chart = nv.models.historicalBarChart();
chart.xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis
.color(['#68c'])
.useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing
.margin({
"left": 80,
"right": 50,
"top": 20,
"bottom": 30,
})
.noData("There is no data to display.")
.duration(0);
var tickMultiFormat = d3.time.format.multi([
["%-I:%M%p", function(d) {
return d.getMinutes();
}], // not the beginning of the hour
["%-I%p", function(d) {
return d.getHours();
}], // not midnight
["%b %-d", function(d) {
return d.getDate() != 1;
}], // not the first of the month
["%b %-d", function(d) {
return d.getMonth();
}], // not Jan 1st
["%Y", function() {
return true;
}]
]);
chart.xAxis
.showMaxMin(false)
.tickPadding(10)
.tickFormat(function(d) {
return tickMultiFormat(new Date(d));
});
chart.yAxis
.tickFormat(d3.format(",.0f"));
var svgElem = d3.select('#chart svg');
svgElem
.datum(data)
.transition()
.call(chart);
// make our own x-axis tick marks because NVD3 doesn't provide any
var tickY2 = chart.yAxis.scale().range()[1];
var lineElems = svgElem
.select('.nv-x.nv-axis.nvd3-svg')
.select('.nvd3.nv-wrap.nv-axis')
.select('g')
.selectAll('.tick')
.data(chart.xScale().ticks())
.append('line')
.attr('class', 'x-axis-tick-mark')
.attr('x2', 0)
.attr('y1', tickY2 + 7)
.attr('y2', tickY2)
.attr('stroke-width', 3);
// set up the tooltip to display full dates
var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p');
var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator();
var tooltip = chart.interactiveLayer.tooltip;
tooltip.contentGenerator(function(d) {
d.value = d.series[0].data.x;
return contentGenerator(d);
});
tooltip.headerFormatter(function(d) {
return tsFormat(new Date(d));
});
return chart;
});
<div>Try resizing the panel to see the various types of time labels.</div>
<br>
<div id="chart">
<svg></svg>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.js"></script>

Unable to supdate chart when switching dataset on button click

The first time I load data, the graph draws correctly, but when I load a different data set, the graph remains unchanged.
I switch between datasets using buttons. The first click always draws the graph correctly, no matter what button I click. But I can't update the graph after it is drawn by clicking on the other button. Any help is very much appreciated,thank you!
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 900;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale
.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
});
bar
.append("rect")
.attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
CodePen: https://codepen.io/rfripp2/pen/porpaLL
This is the expected behavior. Let's look at your code:
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
The select all statement selects all existing elements matching the selector that are children of elements in the selection chart.
The data method binds a new data array to this selection.
The enter method returns a new selection, containing a placeholder for every item in the data array which does not have a corresponding element in the selection.
The append method returns a newly appended child element for every element in the selection it is called on.
Running the code
The first time you call the draw function you have no g elements, so the selection is empty. You bind data to this empty selection. You then use the enter selection. Because there are two data items and no elements in the selection, enter contains two placeholders/elements. You then use append to add those elements.
The second time you call the draw function you have two g elements, so the selection has two elements in it. You bind data to this selection. You then use the enter selection. Because you already have two elements and you only have two data points, the enter selection is empty. As a consequence, append does not create any new elements.
You can see this by using selection.size():
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 900;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale
.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
});
console.log("The enter selection contains: " + bar.size() + "elements")
bar
.append("rect")
.attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Solution
We want to use both the update and the enter selection (if the dataset ever changes in size, we'd likely want the exit selection too). We can use .join() to simplify this, join removes elements in the exit selection (surplus elements which don't have a corresponding data item), and returns the merged enter selection (new elements for surplus data items) and update selection (preexisting elements).
The nesting of your elements into a parent g and child rect is unnecessary here - and requires additional modifications. By positioning the bars directly we avoid the need for the parent g:
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scaleBand().range([0, width], 0.9);
let y = d3.scaleLinear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("rect")
.data(dataSet)
.join("rect")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
This requires updating your version of D3 from v3 (you are actually using two versions of D3, v3 and v4, both fairly outdated, and both with different method names, actually with different ways of handling the enter selection).
If you wish to use d3v4, then the join method is not available, but we can merge enter and update:
When I say update selection, I'm refering to the initial selection:
// update selection:
let bar = chart
.selectAll("rect")
.data(dataSet);
// enter selection:
bar.enter().append("rect")
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scaleBand().range([0, width], 0.9);
let y = d3.scaleLinear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("rect")
.data(dataSet);
bar.enter().append("rect")
.merge(bar)
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.0/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
And lastly, if you wish to keep d3v3 (we are on v7 already), we can rely on an implicit merging of update and enter on enter (modifying the update selection). This "magic" was removed in v4, partly because it was not explicit. To do so we need to break your method chaining so that bar contains the
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
// update selection:
let bar = chart
.selectAll("rect")
.data(dataSet);
// enter selection:
bar.enter().append("rect")
bar.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Note: d3v4 made changes to method names that break code from v3. This required changes to d3.scale.linear / d3.scale.ordinal in the snippets using v4 and 7 (using merge and join respectively).

c3js Multi color design

I've implementing barchart to denote my result set. I am trying to create this design using c3js. I referred the documentation but have not getting the shaded design. Please someone guide me to solve this.
My Code Snippet is,
var chart = c3.generate({
bindto: '#chart',
size : {
width: 600,
height: 200
},
data: {
columns: [
["data1", 40, 20, 20, 20],
["data2", 20, 10, 30, 30]
],
type: 'bar',
groups: [
['data1', 'data2']
],
order: null,
labels: {
format: function(v, id, i, j) {
return v;
}
}
},
bar: {
space: 0.2,
width: {
ratio: 0.2 // this makes bar width 50% of length between ticks
}
},
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.3.0/c3.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.3.0/c3.min.js"></script>
<div id="chart"></div>
My requirement is to design like below image in bars in barchart,
Thanks
The solution in the snippet introduces some d3 SVG manipulation which puts a region over the bars of each targeted series. The region has a hatched grey line and a semi-transparent fill. The function to do this is written to be portable i.e. outside of the C3 construtor params, and is invoked by the onrendered c3 event.
The doClone() function duplicates nodes in place which is useful to know, and the creation of the pattern and use as a colour via 'url(#patternid)' is also a potentially useful technique.
Also available at https://codepen.io/JEE42/pen/yRWbvq
function doClone(node){ // clone the given node
return d3.select(node.parentNode.insertBefore(node.cloneNode(true), node.nextSibling));
}
function hatchBars(hatchTargets){ // Place a hatching pattern over the target bars.
for (var i = 0; i < hatchTargets.length; i = i + 1){
d3.select('.c3-bars-' + hatchTargets[i]).each(function(d, i){
d3.select(this).selectAll('path').each(function(d, i){
var node = d3.select(this).node();
var daClone = doClone(node);
daClone
.style('fill', 'url(#hash4_4)')
.style('stroke', 'url(#hash4_4)');
});
})
}
}
c3.chart.internal.fn.afterInit = function () {
d3.select('defs')
.append('pattern')
.attr('id', "hash4_4") // use id to get handle in a moment
.attr('width', 14)
.attr('height', 14)
.attr('patternUnits', "userSpaceOnUse")
.attr('patternTransform', "rotate(45 0 0 )")
.append("rect")
.attr('width', 14)
.attr('height', 14)
.attr('fill', '#00000000') // transparent background
d3.select('#hash4_4') // get the pattenn
.append('line') // add a line
.attr('y2', 14)
.style('stroke', "#00000044") // semi-transparent bars
.attr('stroke-width', 14)
};
//
// Standard C3 chart render with one twist which is the onrendered event call at the end.
//
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['data1', -30, 200, 200, 400, -150, 250],
['data2', 130, 100, -100, 200, -150, 50],
],
type: 'bar',
groups: [
['data1', 'data2']
]
},
grid: {
y: {
lines: [{value:0}]
}
},
onrendered: function () { // execute after drawn
hatchBars(['data2']); // Place a hatching pattern over the target bars.
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.7/c3.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.7/c3.min.js"></script>
<div class='chart-wrapper'>
<div class='chat' id="chart"></div>
</div>

D3 pie chart is not displaying for me

Hi I am trying to Display D3 pie chart but i am getting only legend symbols ...can someone please help me to display d3 pie chart for dynamic data display.it will not show any errors only legend symbols displayed pie chart is not displaying.
here is the html i am using
<script src="angularjs-nvd3-directives-master/examples/js/angular.js"></script>
<script src="angularjs-nvd3-directives-master/examples/js/d3.js"></script>
<script src="angularjs-nvd3-directives-master/examples/js/nv.d3.js"></script>
<script src="angularjs-nvd3-directives-master/dist/angularjs-nvd3-directives.js"></script>
<link href="angularjs-nvd3-directives-master/examples/stylesheets/nv.d3.css" rel="stylesheet" />
<style>
#chart svg {
height: 295px;
width:300px;
}
</style>
<div id="chart">
<svg></svg>
</div>
and the javascript code i am using is...I want to display pie chart for dynamic data.
$.ajax({
type: "POST",
url: "Assets.asmx/Statereport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
function OnSuccess(data, status) {
var myObject = JSON.parse(data.d);
var source = {
datatype: "json",
datafields: [
{ name: 'totsch' },
{ name: 'districtname' },
{ name: 'statename' }
],
localdata: myObject
};
var dataAdapter = new $.jqx.dataAdapter(source);
var ObjectIDs = [];
for (var i = 0; i < myObject.length; i++) {
ObjectIDs.push(myObject[i].statename);
}
var gridquerystr = ObjectIDs[0].toString();
nv.addGraph(function () {
var chart = nv.models.pieChart()
.x(function (d) { return d.label })
.y(function (d) { return d.value })
.showLabels(false);
d3.select("#chart svg")
.datum(myObject)
.transition().duration(1200)
.call(chart);
return chart;
});
please help me as soon as posssible..... or suggest me any opensource charts for displaying dynamic data using ajax json data . I am new to coding so please help
[![d3 pie chart][1]][1]
[1]: http://i.stack.imgur.com/ppqZf.jpg

How to handle mouseout event on DC range graph

I am using DC chart range filter. I want to handle mouse out event on range filter, so I can handle filter on mouse-out. I had used filter and post-redraw but when I use this there are multiple time event fire on single drag on range chart. I need only the last change event and I think a mouse out or mouse up event would be helpful. Can any one help me with how to use mouse up/mouse out event on range Chart?
chart.on('postRender', function() {
chart.select('.brush').on("mouseover", function() {
console.log('mouseover');
});
chart.select('.brush').on("mouseout", function() {
console.log('mouseout');
});
chart.select('.brush').on("mouseup", function() {
console.log('mouseup')
});
chart.select('.brush').on("click", function() {
console.log('click')
});
});
Working snippet below:
var data = [{
date: "2011-11-21",
total: 90
}, {
date: "2011-11-22",
total: 90
}, {
date: "2011-11-23",
total: 90
}, {
date: "2011-11-24",
total: 200
}, {
date: "2011-11-25",
total: 200
}];
var cf = crossfilter(data);
var timeDimension = cf.dimension(function(d) {
return new Date(d.date);
});
var totalGroup = timeDimension.group().reduceSum(function(d) {
return d.total;
});
var chart = dc.lineChart("#chart")
.width(400)
.height(200)
.x(d3.time.scale().domain(d3.extent(data, function(d) {
return new Date(d.date);
})))
.dimension(timeDimension)
.group(totalGroup)
.renderArea(true)
.brushOn(true);
chart.xAxis().ticks(4);
function caught(eventName) {
document.getElementById(eventName).className = 'bold';
setTimeout(function() {
document.getElementById(eventName).className = '';
}, 750);
}
chart.on('postRender', function() {
chart.select('.brush').on("mouseover", function() {
console.log('mouseover');
caught('mouseover');
});
chart.select('.brush').on("mouseout", function() {
console.log('mouseout');
caught('mouseout');
});
chart.select('.brush').on("mouseup", function() {
console.log('mouseup')
caught('mouseup');;
});
chart.select('.brush').on("click", function() {
console.log('click')
caught('click');;
});
});
chart.render();
<link href="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.11/crossfilter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.js"></script>
<style>
.bold {
font-weight: bold;
}
</style>
<div id="chart"></div>
<div id="mouseout">mouseout</div>
<div id="mouseover">mouseover</div>
<div id="mouseup">mouseup</div>
<div id="click">click</div>

Resources