I am using nvd3.js and trying to add a click event
d3.selectAll(".nv-bar").on('click', function () {console.log("test");});
JSFiddle
How can I do that ?
Just found out that this works as well (at least for multibar charts):
chart.multibar.dispatch.on("elementClick", function(e) {
console.log(e);
});
I had to look at the source in src/multibar.js to find out; since it's there, I guess this is the way it was intended to be done. However, I second what Alex said in his answer: the lack of documentation for NVD3 is a really big disadvantage. Which is sad because the general idea of the project is great: giving us the power of D3 without going into all the details...
I was running into the same issue and was about to dump NVD3 all together because of the lack of documentation... What you need to do is add a callback function to addGraph(). Also note the d3.selectAll() instead of d3.select().
Good Luck.
nv.addGraph(function() {
var chart = nv.models.multiBarHorizontalChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.margin({top: 5, right: 5, bottom: 5, left: 5})
.showValues(false)
.tooltips(true)
.showControls(false);
chart.yAxis
.tickFormat(d3.format('d'));
d3.select('#social-graph svg')
.datum([data])
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
},function(){
d3.selectAll(".nv-bar").on('click',
function(){
console.log("test");
});
});
There are three key points here.
1) No documentation means you have to go through the source code.
2) All graphs have a tooltip, which means events are already firing in the source code.
3) Use the configuration object (in the Documentation) as a road map of the source code.
ie.
var config = {chart: {type: 'multiChart',xAxis:{},yAxis{}}
Open the nvd3/nv.d3.js file
CTRL+F+ the chart type. In this case it is 'multiChart'.
You will see nv.models.multiChart.
Scroll down to find the tooltip events and you will find the needed documentation.
lines1.dispatch.on('elementMouseout.tooltip', function(evt) {tooltip.hidden(true) });
stack1.dispatch.on('elementMouseout.tooltip', function(evt) {tooltip.hidden(true) });
bars1.dispatch.on('elementMouseout.tooltip', function(evt) {tooltip.hidden(true) });
Therefore, to write your own event...
var config = {chart: {type: 'multiChart',
bars1: {
dispatch:{
elementClick:function(e){//do Stuff}
},
xAxis:{},yAxis{}
}
This worked for me: (e.target.data outputs the data attributes attached to that element, like x, y)
$(document).on("click", "#chart svg", function(e) {
console.log (e);
console.log (e.target.__data__);
});
If using AngularJS, use this code in your app.js.
$scope.$on('elementClick.directive', function(angularEvent, event){
console.log(event);
});
This worked for me.
https://bridge360blog.com/2016/03/07/adding-and-handling-click-events-for-nvd3-graph-elements-in-angular-applications/
Just use console.log(e) instead of console.log(e.data) to avoid undefined error.
This coderwall blog heads us the right direction.
chr.scatter.dispatch.on('elementClick', function(event) {
console.log(event);
});
jQuery makes this easy:
$( ".nv-bar" ).click(function() {
console.log("test");
});
Fiddle # http://jsfiddle.net/eTT5y/1/
$('.nv-pie .nv-pie .nv-slice').click(function(){
temp = $(this).text();
alert(temp);
})
This would work fine for the Pie Chart ,Similarly u can go ahead for other charts too....
For stacked area chart, you should disable interactiveGuideline and use elementClick.area:
chart.useInteractiveGuideline(false);
chart.stacked.scatter.dispatch.on("elementClick.area", function(e) {
console.log(e);
});
Just add callback to you options in controller
If using BarChart then replace multibar to discretebar
$scope.options = {
chart: {
type: 'multiBarHorizontalChart',
height: 450,
x: function(d){return d.label;},
y: function(d){return d.value;},
showControls: true,
showValues: true,
duration: 500,
xAxis: {
showMaxMin: false
},
yAxis: {
axisLabel: 'Values',
tickFormat: function(d) {
return d3.format(',.2f')(d);
}
},
callback: function(chart) {
chart.multibar.dispatch.on('elementClick', function(e){
console.log('elementClick in callback', e.data);
});
}
}
};
Related
I am making a stacked line chart for a dashboard:
var json = [...]
var timeFormat = d3.time.format.iso;
json = json.map(function(c){
c.date = timeFormat.parse(c.date);
return c;
});
var data = crossfilter(json);
var days = data.dimension(function (d) {
return d.date;
});
var minDate = days.bottom(1)[0].date;
var maxDate = days.top(1)[0].date;
var lineValues = days.group().reduce(function (acc, cur) {
acc[cur.line] = (acc[cur.line] || 0) + 1
return acc;
}, function (acc, cur) {
acc[cur.line] = (acc[cur.line] || 0) - 1
return acc;
}, function () {
return {};
});
var personChart = dc.lineChart("#graph");
personChart
.turnOnControls(true)
.width(600).height(350)
.dimension(days)
.group(lineValues, "completed")
.valueAccessor(function (d) {
return d.value.completed || 0;
})
.stack(lineValues, "assigned", function (d) {
return d.value.assigned || 0;
})
.stack(lineValues, "inactive", function (d) {
return d.value.inactive || 0;
})
.stack(lineValues, "active", function (d) {
return d.value.active || 0;
})
.stack(lineValues, "new", function (d) {
return d.value.new || 0;
})
.stack(lineValues, "temp", function (d) {
return d.value.temp || 0;
})
.elasticY(true)
.renderArea(true)
.x(d3.time.scale().domain([minDate, maxDate]))
.ordinalColors(colorScale)
.legend(dc.legend().x(50).y(10).itemHeight(13).gap(5).horizontal(true));
dc.renderAll();
Fiddle here
It is working fine so far, but I reached an obstacle. I need to implement an option to filter the chart by individual stacks. Is this possible in dc.js? I can modify and rewrite the entire code if necessary as well as ask my client to remodel the data differently, if needed. There are other fields in the data that I filter on for other charts so preserving that functionality is important.
By design, dc.js has a lot of "leaky abstractions", so there is usually a way to get at the data you want, and customize the behavior by dropping down to d3, even if it's functionality that wasn't anticipated by the library.
Your workaround of using a pie chart is pretty reasonable, but I agree that clicking on the legend would be better.
Here's one way to do that:
var categories = data.dimension(function (d) {
return d.line;
});
personChart
.on('renderlet', function(chart) {
chart.selectAll('.dc-legend-item')
.on('click', function(d) {
categories.filter(d.name);
dc.redrawAll();
})
});
Basically, once the chart is done drawing, we select the legend items and replace the click behavior which our own, which filters on another dimension we've created for the purpose.
This does rely on the text of the legend matching the value you want to filter on. You might have to customize the undocumented interface .legendables() between the legend and its chart, if this doesn't match your actual use case, but it works here.
This fork of your fiddle demonstrates the functionality: https://jsfiddle.net/gordonwoodhull/gqj00v27/8/
I've also added a pie chart just to illustrate what is going on. You can have the legend filter via the pie chart by doing
catPie.filter(d.name);
instead of
categories.filter(d.name);
This way you can see the resulting filter in the slices of the pie. You also can get the toggle behavior of being able to click a second time to go back to the null selection, and clicking on multiple categories. Leave a comment if the toggle behavior is desired and I try to come up with a way to add that without using the pie chart.
Sometimes it seems like the legend should be its own independent chart type...
I am trying all kinds of ways to make .sort() work on my csv dataset. No luck.
I'd just like to sort my data by a "value" column.
This is the function I'm running inside my d3.csv api call and before I select the dom and append my divs:
dataset = dataset.sort(function (a,b) {return d3.ascending(a.value, b.value); });
Before I get to the .sort, I clean the data:
dataset.forEach(function(d) {
d.funded_month = parseDate(d.funded_month);
d.value = +d.value;
});
};
Everything seems in order. When I console.log(d3.ascending(a.value, b.value)), I get the right outputs:
-1 d32.html:138
1 d32.html:138
-1 d32.html:138
1 d32.html:138
etc..
Yet the bars data doesn't sort.
It is not clear from the provided code but I will hazard a guess you are not handling async nature of d3.csv.
This plunkr shows your sort code working fine. Note where the data object is declared, populated, and used.
here is a partial listing. I have added buttons that re-order data. To achieve this we need to put the ordering logic inside render rather than inside the d3.csv callback.
<script type="text/javascript">
var data = [];
d3.csv("data.csv",
function(error, rows) {
rows.forEach(function(r) {
data.push({
expense: +r.expense,
category: r.category
})
});
render();
});
function render(d3Comparator) {
if(d3Comparator) data = data.sort(function(a, b) {
return d3[d3Comparator](a.expense, b.expense);
});
d3.select("body").selectAll("div.h-bar") // <-B
.data(data)
.enter().append("div")
.attr("class", "h-bar")
.append("span");
d3.select("body").selectAll("div.h-bar") // <-C
.data(data)
.exit().remove();
d3.select("body").selectAll("div.h-bar") // <-D
.style("width", function(d) {
return (d.expense * 5) + "px";
})
.select("span")
.text(function(d) {
return d.category;
});
}
</script>
<button onclick="render('ascending')">Sort ascending!</button>
<button onclick="render('descending')">Sort descending!</button>
I'm drawing a scatter plot using d3js and nvd3.js. To fetch and render the data I use:
var chart;
var data;
var url = window.location+"/data";
d3.json(url, function(error, json) {
if (error) return console.warn(error);
data = json;
nv.addGraph(function() {
chart = nv.models.scatterChart()
.showDistX(true)
.showDistY(true)
.useVoronoi(true)
.color(d3.scale.category10().range())
.transitionDuration(300);
chart.xAxis.tickFormat(d3.format('.001f'));
chart.yAxis.tickFormat(d3.format('.02f'));
chart.tooltipContent(function(key){
var result = '<h2>'+ key + '</h2>';
return result;
});
d3.select('#div2 svg')
.datum(data)
.call(chart);
nv.utils.windowResize(chart.update);
chart.dispatch.on('stateChange', function(e) { ('New State:', JSON.stringify(e)); });
return chart;
});
});
Unfortunately the server the data comes from takes up to 2 minutes to render all the data. So my function times out. How can I increase the timeout value, so the graph actually displays?
First, 2 minutes to render a graph is very long. You should try to find a solution to get data faster from your server (using caching for example).
If you want to do fancy requests for data, a good method is to fall back on jQuery.ajax(). This function offers a timeout parameter that is probably what you are looking for.
You would end up having something like:
function handleSuccess(data) {
nv.addGraph(function() {
chart = nv.models.scatterChart()
.showDistX(true)
.showDistY(true)
.useVoronoi(true)
.color(d3.scale.category10().range())
.transitionDuration(300);
chart.xAxis.tickFormat(d3.format('.001f'));
chart.yAxis.tickFormat(d3.format('.02f'));
chart.tooltipContent(function(key){
var result = '<h2>'+ key + '</h2>';
return result;
});
d3.select('#div2 svg')
.datum(data)
.call(chart);
nv.utils.windowResize(chart.update);
chart.dispatch.on('stateChange', function(e) { ('New State:', JSON.stringify(e)); });
return chart;
});
}
handleError: function(error) {
return console.warn(error);
}
$.ajax({
url: url,
type: 'GET',
timeout: 3000, // in milliseconds
dataType: 'json'
success: handleSuccess,
error: handleError
})
You can also have a look at the request documentation page in d3. This answer can also help: https://stackoverflow.com/a/17320249/1041692
Any ideas on why this won't work. I am using the tutorial from CSS-Tricks using AJAX to load pages dynamically. This works fine up until I introduced a secondary navigation on some pages which caused pages to load normally.
This is the code I am using. I am using classes to style the different nav areas.
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
Website: http://darynjohnson.com/Medical%20Futures/about.php
Those new created links do not have any events bound to them because u set delagate function on the the object which is not changed. New added objects with the same tag ("nav" here) won't get delagation.
Use:
$('#page').delegate("nav a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
Also I recommend you to upgrade jQuery to the newest version and replace delegate() with on()
I'm using the latest version of jqPlot (v1.0.0b2_r1012) to plot my histograms.
To catch a single click event I'm using 'jqplotDataClick' as follows:
$('#myHistogram').bind('jqplotDataClick', function(ev, seriesIndex, pointIndex, data) {
// Do something
});
Is it possible to catch a double click event instead?
Unfortunately I've been unable to find such event in jqplot.barRenderer.js.
Update:
I've made the following two changes to my jqplot.barRenderer.js file:
Register jqplotDblClick event
$.jqplot.BarRenderer.prototype.init = function(options, plot) {
...
...
plot.postInitHooks.addOnce(postInit);
plot.postDrawHooks.addOnce(postPlotDraw);
plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
plot.eventListenerHooks.addOnce('jqplotMouseDown', handleMouseDown);
plot.eventListenerHooks.addOnce('jqplotMouseUp', handleMouseUp);
plot.eventListenerHooks.addOnce('jqplotClick', handleClick);
plot.eventListenerHooks.addOnce('jqplotDblClick', handleDblClick);
//$.jqplot.eventListenerHooks.push(['jqplotDblClick', handleDblClick]); I've also tried this but without any luck
plot.eventListenerHooks.addOnce('jqplotRightClick', handleRightClick);
};
Implement handleDblClick function
function handleDblClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var evt = jQuery.Event('jqplotDataDblClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
And then I bind jqplotDataDblClick in my JavaScript file as follows:
$('#myHistogram').bind('jqplotDataDblClick', function(ev, seriesIndex, pointIndex, data) {
alert("Ohayo!"); // Good morning in Japanese
});
However the double click event doensn't get fired when I double click on one of my vertical bar graphs. I've tried binding "jqplotRightClick" but that doesn't work either. If I use "jqplotClick" then everything works as expected.
Does anyone know what I am doing wrong here?
Update 2:
RE: I've tried binding "jqplotRightClick" but that doesn't work either. (see above)
I've just found out that in order to catch this event you have to set the following:
captureRightClick: true,
See: How to capture right click event
From the "cursor" plugin, they handle it like this:
if (c.dblClickReset) {
$.jqplot.eventListenerHooks.push(['jqplotDblClick', handleDblClick]);
}
EDITS
I can capture the double click by just binding the 'jqplotDblClick'. I did not have to push the event. Sorry for the misdirection, my answer above meant to show that the event already existed. See working fiddle here. The only additional thing I added was CSS rules to make the div un-selectable since a double-click will select it.
HTML:
<div id="chart1" style="margin-top:20px; margin-left:20px; width:300px; height:300px; -moz-user-select: -moz-none;-khtml-user-select: none;-webkit-user-select: none;-ms-user-select: none;user-select: none;"></div>
JS:
$(document).ready(function(){
$.jqplot.config.enablePlugins = true;
var s1 = [2, 6, 7, 10];
var ticks = ['a', 'b', 'c', 'd'];
plot1 = $.jqplot('chart1', [s1], {
seriesDefaults:{
renderer:$.jqplot.BarRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
}
});
$('#chart1').bind('jqplotDblClick',
function (ev, seriesIndex, pointIndex, data) {
alert('hi');
});
});