I'm looking for a chart for displaying my values over a long time period. The problem is due to the timeline most charts are useless because there are to many points in it and I can't zoom in or out.
So I'm looking for a chart where I load my complete data and the user can choose which data he wants (e.g. Values1, values2) and click into the chart to see only that timespan he wants.
A perfect example is http://dataaddict.fr/prenoms but I don't know where to find a similar chart that I could use. I searched for hours but didn't find anything similar. On the left side the user could choose the data he wants and under the charts the user can choose the timespan.
I hope someone has a good tip for me :) Thanks!
Disclaimer: I am new at javascript and d3.js, so please be skeptical of everything I say, but I will try to help you.
I was able to solve a similar problem by creating a set of regular HTML buttons below the chart (with svg rects inside of each button to create a color square in each button).
//Create the legend div
var legendHtml = "<div style='width:" + (w+marginLeft+marginRight) + "px;'>";
//Size of Squares in legend buttons
var legendRectSize = 9;
//Create a button for each item
varNames.forEach(function(element, index){
legendHtml = legendHtml + "<button class='legend clickable active' id='" + varNames[index] + "'><svg width='9' height='9'><g><rect width='"+legendRectSize+"' height='"+legendRectSize+"' style='fill:" + color(varNames[index]) + ";'></rect></g></svg> " + varNames[index] + "</button>";
});
//Close out the legend div
legendHtml = legendHtml + "</div>";
I then added the a new legend div below my chart, which happened to be in a div with the id "employment."
//Add the legend div to the bottom of the chart
var legendDiv = document.createElement("div");
var legendIdAtt = document.createAttribute("id");
legendIdAtt.value = "legend";
legendDiv.setAttributeNode(legendIdAtt);
document.getElementById('employment').appendChild(legendDiv);
document.getElementById('legend').innerHTML = legendHtml;
Finally, I added an event listener to the legend (specifically the class 'clickable') that updates the chart by updating, adding, or removing the new data. I used jquery to do this because I was finding the the built in d3.on() method was not working on nodes that are dynamically created after the document loads.
//Event listener for updating the chart
$('body').on('click', '.clickable', function () {
var id = $(this).attr('id');
//Toggle the buttons active or not active
if ($(this).hasClass("active")) {
$(this).removeClass("active");
} else {
$(this).addClass("active");
}
change(id);
});
Your change function will be different depending on what you want to do, but in my case, I made sure that the id for the buttons was the same as the variable names in the data (I originally set the id by calling the variable names), and then went through the general update pattern to updates my line graph. This article helped me understand d3's general update pattern: http://bl.ocks.org/mbostock/3808218
Hope that helps! Cheers!
Edit:
You should be able to make one set of buttons that adds, updates, and subtracts data based on the data the user wants to add to the cart using this approach. You could use a similar method to create a set of html buttons that, when clicked, update the domain of the x scale.
Related
I'm having a problem with tracking Transforms across page loads, any help much appreciated.
'workspaceDiv' is a full page outer div
'squaregroup' is a g that contains all page elements and can be moved around
For this example I've added a single circle to the squaregroup
workspaceDiv = d3.select("#workspaceDiv")
squaregroup = workspaceDiv.append("g")
.attr("id", "squaregroup")
squaregroup.append("circle").attr("cx", 20).attr("cy", 20).attr("r", 10);
To allow the user to move the g around the page I've attached a d3.zoom.
workspaceDiv.call(zoom);
var zoom = d3.zoom()
.on("zoom", zoomed)
function zoomed(){
squaregroup.attr("transform", d3.event.transform)
}
You might have noticed that I want to transform squaregroup but I have attached the d3.zoom to the workspaceDiv. This is so you can transform it by clicking anywhere on the page (and not only by clicking in the small squaregroup).
On initial page load, this works perfect. Any transforms are also saved as a string in the URL successfully.
On a page reload, the transform is taken from the URL and applied to the sqauregroup:
squaregroup.attr("transform", d3.zoomIdentity.translate(url.x,url.y).scale(url.scale))
Chrome devtools showing the custom transform applied after page reload
[2]: https://i.stack.imgur.com/H93Nf.png
The problem
After a page reload, squaregroup is transformed (see image above), but the d3.event.transform of workspaceDiv is reset, meaning the first drag (of 1 pixel), resets transform (to 0,0) and not with the transform I've applied (200,400).
So the 2nd+ drag is fine, but the first drag throws all data off the page meaning you have to drag around until you find it.
Approaches
Attaching ".call(zoom)" on g means the draggable area is too small, and completely changes the behaviour for the user
I can't find a way to force update the tracking of a .event to be in sync after a page reload
I'm not sure if my approach is wrong, or if there is a function of d3.zoom I just can't find. Any input welcomed!
Many Thanks
Here is the solution (see it in a fiddle)
Make sure you are using zoomIdentity according to the D3 V5 and higher (the sample you tried to use is probably done for the previous versions):
const svg = d3.select('svg');
const group = svg.append('g');
group.append('circle').attr('r', 20);
const zoom = d3.zoom();
const onZoom = () => group.attr('transform', d3.event.transform);
zoom.on("zoom", onZoom);
svg.call(zoom);
const transform = d3.zoomIdentity;
transform.x = 100;
transform.y = 50;
group.call(zoom.transform, transform);
I have an heatmap that show some data and a sparkline for each line of the heatmap.
If the user click on a row label, then the data are ordered in decreasing order, so each rect is placed in the right position.
Viceversa, if the user click on a column label.
Each react is placed in the right way but I'm not able to place the sparkline.
Here the code.
When the user click on a row label, also the path inside the svg containing the sparkline should be updated.
And then, when the user click on a column label, the svg containing the sparkline should be placed in the correct line.
To place the svg in the right place, I try to use the x and y attributes of svg. They are updated but the svg doesn't change its position. Why?
Here is a piece of code related to that:
var t = svg.transition().duration(1000);
var values = [];
var sorted;
sorted = d3.range(numRegions).sort(function(a, b) {
if(sortOrder) {
return values[b] - values[a];
}
else {
return values[a] - values[b];
}
});
t.selectAll('.rowLabel')
.attr('y', function(d, k) {
return sorted.indexOf(k) * cellSize;
});
Also, I don't know how to change the path of every sparkline svg. I could take the data and order them manually, but this is only good for the row on which the user has clicked and not for all the others.
How can I do?
The vertical and horizontal re-positioning/redrawing of those sparklines require different approaches:
Vertical adjustment
For this solution I'm using selection.sort, which:
Returns a new selection that contains a copy of each group in this selection sorted according to the compare function. After sorting, re-inserts elements to match the resulting order.
So, first, we set our selection:
var sortedSVG = d3.selectAll(".data-svg")
Then, since selection.sort deals with data, we bind the datum, which is the index of the SVG regarding your sorted array:
.datum(function(d){
return sorted.indexOf(+this.dataset.r)
})
Finally, we compare them in ascending order:
.sort(function(a,b){
return d3.ascending(a,b)
});
Have in mind that the change is immediate, not a slow and nice transition. This is because the elements are re-positioned in the DOM, and the new structure is painted immediately. For having a slow transition, you'll have to deal with HTML and CSS inside the container div (which may be worth a new specific question).
Horizontal adjustment
The issue here is getting all the relevant data from the selection:
var sel = d3.selectAll('rect[data-r=\'' + k + '\']')
.each(function() {
arr.push({value:+d3.select(this).attr('data-value'),
pos: +d3.select(this).attr('data-c')});
});
And sorting it according to data-c. After that, we map the result to a simple array:
var result = arr.sort(function(a,b){
return sorted.indexOf(a.pos) - sorted.indexOf(b.pos)
}).map(function(d){
return d.value
});
Conclusion
Here is the updated Plunker: http://next.plnkr.co/edit/85fIXWxmX0l42cHx or http://plnkr.co/edit/85fIXWxmX0l42cHx
PS: You'll need to re-position the circles as well.
I have a an AmChart, JavaScript chart, column chart with scroll.
I'd like to be able to pull the category axis data for the min and the max values that are currently being displayed in the chart.
Example:
If I have 0-10 on the x-axis and I zoom to 4-6, I want to be able to reference the data on point 4 and point 6.
I am new to AmCharts so hopefully I am just missing something simple but I can't seem to figure this out.
Here is a link to a chart I made:
https://live.amcharts.com/U4YmV/
You can use the zoomed event to capture the startIndex and endIndex from its event object.
In the example below, zoomedData is the zoom selection.
chart.addListener("zoomed", zoomed);
function zoomed (e) {
var chart = e.chart,
data = chart.dataProvider,
zoomedData = data.slice(e.startIndex, e.endIndex + 1);
}
Please check the example here: https://codepen.io/team/amcharts/pen/246e8f826610e848b7389fb85657348a
Good day all
I am having a bit of trouble. I have a graph that ranges from 2012 to 2015. I need my year to display at my origin once I zoom in. At this stage my the year only displays at the beginning of every year. It takes the place of January. Is it possible to do this?
chart3.addListener("zoomed", function(e) {
var date = $( ".chartdiv3 .amChartsPeriodSelector .amChartsInputField" )
.map(function() {
return $(this).val();
}).get();
$(this).html(date.join(' <i style="color: #F47C00;">to</i> '));
chart3.panels[0].titles[1].text = "period - " + date[0] + " to " + date[1];
chart3.panels[0].validateData();
});
chart3.write('chartdiv3');
Ok. So changing the labelFunction depending on zoom is pretty easy.
Just take a look at this fiddle. (I used this as template).
The other approach is not as easy as i thought. You can modify the labels when the zoomed event is fired, however i haven't found a way to get the year for the first label. (it's an amcharts object containing the svg but no date, just the plain text for the label)
I have a composite chart of 2 line charts however I need to add a third chart to it.
This third chart will have these unique properties:
The data will come in via an ajax call and be available as a two dimensional array [[timestamp,value],[timestamp,value]...]
Every new ajax call needs to replace the values of the previous one
It does not need to respect any of the filters and will not be used on any other charts
It will however need to use a differently scaled Y axis.. (and labeled so on the right)
This is how the chart currently looks with only two of the charts
This is my code with the start of a third line graph... Assuming I have the array of new data available i'm at a little loss of the best/simplest way to handle this.
timeChart
.width(width).height(width*.333)
.dimension(dim)
.renderHorizontalGridLines(true)
.x(d3.time.scale().domain([minDate,maxDate]))
.xUnits(d3.time.months)
.elasticY(true)
.brushOn(true)
.legend(dc.legend().x(60).y(10).itemHeight(13).gap(5))
.yAxisLabel(displayName)
.compose([
dc.lineChart(timeChart)
.colors(['blue'])
.group(metric, "actual" + displayName)
.valueAccessor (d) -> d.value.avg
.interpolate('basis-open')
.dimension(dim),
dc.lineChart(timeChart)
.colors(['red'])
.group(metric, "Normal " + displayName)
.valueAccessor (d) -> d.value.avg_avg
.interpolate('basis-open'),
dc.lineChart(timeChart)
.colors(['#666'])
.y()#This needs to be scaled and labeled on the right side of the chart
.group() #I just want to feed a simple array of values into here
])
Also side note: I've noticed what I might be a small bug with the legend rendering. As you can see in the legend both have the same label but i've used different strings in the second .group() argument.
I believe you are asking a few questions here. I will try to answer the main question: how do you add data to a dc chart.
I created an example here: http://jsfiddle.net/djmartin_umich/qBr7y/
In this example I simply add random data to the crossfilter, though this could easily be adapted to pull data from the server:
function AddData(){
var q = Math.floor(Math.random() * 6) + 1;
currDate = currDate.add('month', 1);
cf.add( [{date: currDate.clone().toDate(), quantity: q}]);
$("#log").append(q + ", ");
}
I call this method once a second. Once it completes, I reset the x domain and redraw the chart.
window.setInterval(function(){
AddData();
lineChart.x(d3.time.scale().domain([startDate, currDate]));
dc.redrawAll();
}, 1000);
I recommend trying to get this working in isolation before trying to add the complexity of multiple y-axis scales.
Currently your best bet is to create a fake group. Really the .data method on the charts is supposed to do this, but it doesn't work for charts that derive from the stack mixin.
https://github.com/dc-js/dc.js/wiki/FAQ#filter-the-data-before-its-charted