Always having the year display at my origin of a graph in AMCharts - amcharts

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)

Related

Plottable.js entityNearest not giving me the nearest entity

Im implementing the code below in a React, Typescript project.
When hovering over my graph I don't get the nearest entity its roughly 5 years off, on my x-axis(time).
I've tried switching out entityNearest for entityNearestXThenY but it yielded similar results.
Below is my pointer interaction function:
new Plottable.Interactions.Pointer()
.attachTo(Chart)
.onPointerMove(function(p) {
var entity = hiddenGraph.entityNearest(p);
var date = parseTime(entity.datum.x);
var value = currencySymbolNoPrecision(entity.datum.y);
var displayValue = (value + " • " + date);
guideline.value(entity.datum.x);
xAxis.annotatedTicks([entity.datum.x]);
title.text(displayValue).yAlignment();
})
.onPointerExit(function() {
guideline.pixelPosition(-10);
xAxis.annotatedTicks([]);
});
Pointer tracking is also very jumpy. My dataset is the gold price per month since 1950. I've checked the dataset to ensure that there are no problems there.
In the image below my mouse is hovering roughly where the red circle is.
Please let me know if I can provide any further information.
I eventually reached a solution by directly editing the coordinates of the mouse after it had bean calculated:
.onPointerMove(p){
p={x: p.x-(compensationValue), y:p.y}
...
...
...
}
While I understand this is by far not the best solution to the problem I had, it has managed to resolve the problem and seemingly with no adverse effects on different screen sizes or when nesting components.

dc.js Composite Graph - Plot New Line for Each Person

Good Evening Everyone,
I'm trying to take the data from a database full of hour reports (name, timestamp, hours worked, etc.) and create a plot using dc.js to visualize the data. I would like the timestamp to be on the x-axis, the sum of hours for the particular timestamp on the y-axis, and a new bar graph for each unique name all on the same chart.
It appears based on my objectives that using crossfilter.js the timestamp should be my 'dimension' and then the sum of hours should be my 'group'.
Question 1, how would I then use the dimension and group to further split the data based on the person's name and then create a bar graph to add to my composite graph? I would like for the crossfilter.js functionality to remain intact so that if I add a date range tool or some other user controllable filter, everything updates accordingly.
Question 2, my timestamps are in MySQL datetime format: YYYY-mm-dd HH:MM:SS so how would I go about dropping precision? For instance, if I want to combine all entries from the same day into one entry (day precision) or combine all entries in one month into a single entry (month precision).
Thanks in advance!
---- Added on 2017/01/28 16:06
To further clarify, I'm referencing the Crossfilter & DC APIs alongside the DC NASDAQ and Composite examples. The Composite example has shown me how to place multiple line/bar charts on a single graph. On the composite chart I've created, each of the bar charts I've added a dimension based off of the timestamps in the data-set. Now I'm trying to figure out how to define the groups for each. I want each bar chart to represent the total time worked per timestamp.
For example, I have five people in my database, so I want there to be five bar charts within the single composite chart. Today all five submitted reports saying they worked 8 hours, so now all five bar charts should show a mark at 01/28/2017 on the x-axis and 8 hours on the y-axis.
var parseDate = d3.time.format('%Y-%m-%d %H:%M:%S').parse;
data.forEach(function(d) {
d.timestamp = parseDate(d.timestamp);
});
var ndx = crossfilter(data);
var writtenDimension = ndx.dimension(function(d) {
return d.timestamp;
});
var hoursSumGroup = writtenDimension.group().reduceSum(function(d) {
return d.time_total;
});
var minDate = parseDate('2017-01-01 00:00:00');
var maxDate = parseDate('2017-01-31 23:59:59');
var mybarChart = dc.compositeChart("#my_chart");
mybarChart
.width(window.innerWidth)
.height(480)
.x(d3.time.scale().domain([minDate,maxDate]))
.brushOn(false)
.clipPadding(10)
.yAxisLabel("This is the Y Axis!")
.compose([
dc.barChart(mybarChart)
.dimension(writtenDimension)
.colors('red')
.group(hoursSumGroup, "Top Line")
]);
So based on what I have right now and the example I've provided, in the compose section I should have 5 charts because there are 5 people (obviously this needs to be dynamic in the end) and each of those charts should only show the timestamp: total_time data for that person.
At this point I don't know how to further breakup the group hoursSumGroup based on each person and this is where my Question #1 comes in and I need help figuring out.
Question #2 above is that I want to make sure that the code is both dynamic (more people can be handled without code change), when minDate and maxDate are later tied to user input fields, the charts update automatically (I assume through adjusting the dimension variable in some way), and if I add a names filter that if I unselect names that the chart will update by removing the data for that person.
A Question #3 that I'm now realizing I'll want to figure out is how to get the person's name to show up in the pointer tooltip (the title) along with timestamp and total_time values.
There are a number of ways to go about this, but I think the easiest thing to do is to create a custom reduction which reduces each person into a sub-bin.
First off, addressing question #2, you'll want to set up your dimension based on the time interval you're interested in. For instance, if you're looking at days:
var writtenDimension = ndx.dimension(function(d) {
return d3.time.hour(d.timestamp);
});
chart.xUnits(d3.time.hours);
This will cause each timestamp to be rounded down to the nearest hour, and tell the chart to calculate the bar width accordingly.
Next, here's a custom reduction (from the FAQ) which will create an object for each reduced value, with values for each person's name:
var hoursSumGroup = writtenDimension.group().reduce(
function(p, v) { // add
p[v.name] = (p[v.name] || 0) + d.time_total;
return p;
},
function(p, v) { // remove
p[v.name] -= d.time_total;
return p;
},
function() { // init
return {};
});
I did not go with the series example I mentioned in the comments, because I think composite keys can be difficult to deal with. That's another option, and I'll expand my answer if that's necessary.
Next, we can feed the composite line charts with value accessors that can fetch the value by name.
Assume we have an array names.
compositeChart.shareTitle(false);
compositeChart.compose(
names.map(function(name) {
return dc.lineChart(compositeChart)
.dimension(writtenDimension)
.colors('red')
.group(hoursSumGroup)
.valueAccessor(function(kv) {
return kv.value[name];
})
.title(function(kv) {
return name + ' ' + kv.key + ': ' + kv.value;
});
}));
Again, it wouldn't make sense to use bar charts here, because they would obscure each other.
If you filter a name elsewhere, it will cause the line for the name to drop to zero. Having the line disappear entirely would probably not be so simple.
The above shareTitle(false) ensures that the child charts will draw their own titles; the title functions just add the current name to those titles (which would usually just be key:value).

dc.js barChart first and last bar not displaying fully

I have a barChart with a d3.time.scale x-axis. I am displaying some data per hour, but the first and last data point bars are always cut in half when using centerBar(true).
(When using centerBar(false) the last bar disappears completely.)
The time window is based upon the data itself and is calculated as follows:
var minDate = dateDim.bottom(1)[0]["timestamp"];
var maxDate = dateDim.top(1)[0]["timestamp"];
.x(d3.time.scale().domain([minDate, maxDate]));
The last line sets the time scale domain to use min and maxDate.
This is how it looks:
I have increased the bar width slightly using .xUnits(function(){return 60;}) as the default is so thin that the first bar disappears within the y-axis.
Also I already tried to change the domain by substracting/adding one hour to min/maxDate, but this results in unexpected behaviour of the first bar.
I used the following to calculate the offset:
minDate.setHours(minDate.getHours() - 1);
maxDate.setHours(maxDate.getHours() + 1);
Is there a fix or workaround for this to add padding before the first and after the last bar?
Subtract an hour from the minDate and add an hour to the maxDate to get an hour worth of padding on each side of your min and max data.
The trick here is to use d3.time.hour.offset and play with offsets until it looks nice.
.x(d3.time.scale().domain([d3.time.hour.offset(minDate, -1), d3.time.hour.offset(maxDate, 2)])); `
See this fiddle http://jsfiddle.net/austinlyons/ujdxhd27/3/
The mistake was not realising JavaScript's passing-by-reference when using objects such as Date objects.
In addition to Austin's answer, which did solve the problem by using d3 functionality, I investigated why my initial attempt by modifying the minDate and maxDate variables failed.
The problem is that when creating the variables
var minDate = dateDim.bottom(1)[0]["timestamp"];
var maxDate = dateDim.top(1)[0]["timestamp"];
I created pointers to the actual data instead of creating new objects with the same value as the minDate and maxDate objects. The line
minDate.setHours(minDate.getHours() - 1);
therefore then manipulated the actual underlying data within the date dimension dateDim, which then led to the peculiar behaviour.
The obvious solution would have been to create new Date() objects like this:
var minDate = new Date(dateDim.bottom(1)[0]["timestamp"]);
var maxDate = new Date(dateDim.top(1)[0]["timestamp"]);
and then do the desired manipulations:
minDate.setHours(minDate.getHours() - 1);
maxDate.setHours(maxDate.getHours() + 1);

Chart to display data over a long time frame

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.

Simple way to add raw data to dc.js composite chart via Ajax

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

Resources