How to add a highlight mark/area to a chart? - javascript

I have a time series chart created using D3 js. I wanted to add highlight areas for certain time intervals to show certain activity occurred during that particular time (there will be different types of activities so each highlight mark will have different color based on its type). I want this highlight area to cover the whole chart vertically from top to bottom.
Here is a sample:
I came across this question which shows how to do it using highcharts.
As of now I use another charting library and I draw an area chart whenever I want to display such highlight areas. Is there a better way to do it using d3 js or should I draw a set of area charts?

I saw this question once. Time for example.
You can combine area and line chart together.
// y.domain()[1] so area is drawn to cover all chart
var area = d3.svg.area()
.interpolate("basis")
.x(function(d) { return x(d.x_axis); })
.y0(height)
.y1(function(d) { return y(y.domain()[1]); });
var line = d3.svg.line()
.x(function(d) { return x(d.x_axis); })
.y(function(d) { return y(d.y_axis); });
Here's an example of AAPL stock chart with highlight from 2012-04-13 to 2012-04-17.
http://vida.io/documents/TzcZJX4itBebKciQZ
Full code:
https://gist.github.com/dnprock/dea634bfdb3c33149c61

Related

Vertical line in D3 plot move on zoom/pan

I am trying to draw a vertical line marker in my graph in D3. It is modeled off of this example: https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172
My issue is that after I draw my line, it doesn't move as I zoom/scroll the graph. An example is shown below:
Currently, I have it calculated as a d3.area().
this.pastDateArea = d3.area()
.x(function(d) { return this.x(this.props.pastDate.toDate()) }.bind(this))
.y0(0)
.y1(function(d) { return this.height }.bind(this))
It is appended as
var pastDateData = [{x:this.props.pastDate.toDate(), y:150}]
this.focus.append("path")
.datum(pastDateData)
.attr("class", "area")
.attr("d", this.pastDateArea)
and zoomed/brushed using
//zoom
var t = d3.event.transform;
this.x.domain(t.rescaleX(this.x2).domain());
//brush
this.svg.select(".zoom").call(this.zoom.transform, d3.zoomIdentity
.scale(this.width / (s[1] - s[0]))
.translate(-s[0], 0));
I know there are similar questions to this one (namely, Draw a vertical line representing the current date in d3 gantt chart) but none of them include the zooming/panning features I have in my graph.
Please let me know if you need more information and thanks!
The issue is that you are not updating the vertical bar with each zoom event. Using the code of the example you show, several things are done when the chart is zoomed, including as you note:
x.domain(t.rescaleX(x2).domain()); // update x scale
focus.select(".area").attr("d", area); // redraw chart area
While you do give the new area the class of area, d3.select will only pick the first matching element. So, on zoom, only one .area element is updated (the first encountered, generally the first appended). But, replacing this with d3.selectAll(".area") will not generate the intended results as the area function referenced (.attr("d",area) ) is only used for the first area (that of the graph, not of the vertical bar).
A solution is to select each area (the chart and the bar) independently and update the area with their respective area generators. To do so, append the vertical bar with a unique class name, or an id and use that to select it later. Then when updating the graph on zoom or brush you can use:
x.domain(s.map(x2.invert, x2)); // update x scale
focus.select(".area").attr("d", area); // redraw chart area
focus.select(".bar").attr("d", pastDateArea);// redraw vertical bar
Remember that this needs to be done for both zoom and brush. Also, in the given example, a clip path is assigned in the css for .area, so you need to keep that in mind as well.
Here's a modified example.

Hide x-axis labels but show tooltips in chart.js

I found many answers how to hide every nth label and yet still be able to show it in the tooltip. But there's a catch. If the label is very long, then the chart would be drawn somehow squished to the top of the canvas. It's logical. But is there any way to hide the labels, still show them in the tooltips and yet ignore them while calculating the y-values? So that the line can be drawn from top to bottom of the canvas?
Thank you for any advice!!
You can extend the line chart to do this. Adapted from Hide labels on x-axis ChartJS (which was for bar charts) with some unneeded code removed.
What we do is pretty simple, we first set the labels array to blanks, allow the initialization to happen and finally loop through the points for the (first) dataset and set the labels to the original labels.
Chart.types.Line.extend({
name: "LineAlt",
initialize: function(data){
var originalLabels = data.labels;
data.labels = data.labels.map(function() { return '' });
Chart.types.Line.prototype.initialize.apply(this, arguments);
this.datasets[0].points.forEach(function(bar, i) {
bar.label = originalLabels[i];
});
}
});
It's enough that you set the labels for the first dataset even if you have multiple datasets - when building a multiTooltip, the label is picked from the first dataset.
Fiddle - http://jsfiddle.net/xjchy2dn/

Remove the Legend from nvd3 pie chart [duplicate]

This question already has an answer here:
How to disable legend in nvd3 or limit it's size
(1 answer)
Closed 7 years ago.
Im working on creating a pie chart using nvd3. I successfully got the pie chart but when the number of slices increase the legends tend to take up lot of space and the pie shrinks. I have decided to remove the legends completely.
i tried somthing like
d3.select(".nv-legendWrap")
.remove();
This hides the legends from being visible but the space is still blank. i want the pie to resize and take up the entire space. How do i do this??
The pie chart looks like this http://i.stack.imgur.com/jkIsG.png
I want the legends specified in the red block to be removed and the pie re-sized to fill the space.
what about hidden the legend by the moment of the creation of the chart:
nv.addGraph(function() {
var chart = nv.models.lineChart().margin({left: 100})
.useInteractiveGuideline(true)
.transitionDuration(350)
.showLegend(false) // <-----Show the legend
.showYAxis(true)
.showXAxis(true);

NVD3.js piechart use in Leaflet control

I am trying to add some data visualization to web map I am working on and I am exploring the use of D3, specifically NVD3. I am using the PieChart Example as a test run for a proof of concept.
I add a leaflet control to my map like this (forgive the bad formatting):
var visualizationControl = L.control({ position: 'bottomleft' });
var visualizationDiv = L.DomUtil.get("visualizationContainerDiv");
// ...
visualizationControl.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'control');
this._div.innerHTML = result;
return this._div;
}
visualizationControl.addTo(MapProvider.map);
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") //div with chart Id and svg container within that div
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
The chart will render ok in my control, and the on hover behaviour does register correctly.
However, when it appends the tooltip to the DOM it appends it to the body instead of my SVG or even the control div.
It's difficult to tell from this image but this was taken during an on.hover over one of the slices of the pie and it should write out the tooltip on top of the pie slice. Notice the "One 29.77" sitting off to the side in the navbar.
I have been poking around the development version of the NVD3 js and found a few blocks that refer to the tooltip container and it looks like it should append it to the SVG container.
I also tried changing the css of the tooltip to no avail.
I don't want to give up on this just yet. Any suggestions, help, ideas would be greatly appreciated. Thanks.
Using the current versions of leaflet, D3 and NVD3, debugging/testing in Chrome.
UPDATE
I did not solve this problem using NVD3 I did, however, end up using C3js. It also has a pie chart and this played nicely with my L.control(). A word of caution though, (if you try to go with C3) look carefully at how the charts are looking to receive the data that is being passed to them. I had to play with this for while to get them to work.

draw only grouped multibar chars using nvd3

I draw a multibarChart using nvd3 library and it 's working very well but it gives me two radio buttons to choose wether i want stacked bars or grouped bars.
Can i disable this and make it only show grouped bars?
This is the javascript code :
nv.addGraph(function() {
var chart = nv.models.multiBarChart();
chart.xAxis.tickFormat(d3.format(',f'));
chart.yAxis.tickFormat(d3.format(',.1f'));
var x = data();
d3.select('#chart svg').datum(data()).transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
The code below will show you bars in a Grouped manner while hiding the controls to the flip between Stacked/Grouped
var chart = nv.models.multiBarChart().stacked(false).showControls(false);
Hope it helps.

Categories