I'm trying to use the zoomToDates function on render of an amCharts Gantt plot: http://jsfiddle.net/Lw2bhxm0/1/
// Doesn't appear to work right...only a few of the events are shown
chart.addListener("rendered", function(event) {
event.chart.zoomToDates(new Date(2016, 1, 1), new Date(2016, 1, 2));
});
The result is much different than if I zoomed to the dates by conventional slider bars or by click and drag. Further, if I try to zoom to a date outside of the data range, it zooms to this same period with missing data. Am I using this wrong or is it a bug?
zoomToDates is a categoryAxis-based function, however the Gantt chart uses a date-based valueAxis to plot dates. You have to call the chart valueAxis' zoomToValues method instead:
chart.addListener("rendered", function(event) {
event.chart.valueAxis.zoomToValues(new Date(2016, 1, 1), new Date(2016, 1, 2));
});
Note: zoomToValues only accepts Date objects and millisecond values for a date-based valueAxis unlike zoomToDates, which can also accept string-based dates. You can use AmCharts.stringToDate to convert string-based dates to Date objects for use with zoomToValues, e.g. chart.zoomToValues(AmCharts.stringToDate("2016-02-01", "YYYY-MM-DD"), AmCharts.stringToDate("2016-02-02", "YYYY-MM-DD"));
Updated fiddle
Related
I'm building a data dashboard using DC.js and was wondering if it was possible to change the color of the slices in a pie chart dynamically based on the value in the field it is referring to.
Basically I've built a pie chart aggregating the costume colors of different superheroes and I'd love to be able to color each slice with the color it is referring to - so the slice for 'Black' is colored black, the slice for 'Green' is colored green and so forth.
I'm fairly new to DC.js so accept that it may not be possible, but wanted to throw it out there and see if it could be done!
I tried including an array within .ordinalColors but couldn't figure out if there was a way to pull in the data from the field dynamically. I'm assuming that I'd have to change the data in the .csv file to a string that could be recognised as a color reference, but not sure how to go about doing that.
function show_costume_color(ndx) {
var costume_color_dim = ndx.dimension(dc.pluck('Costume Colour'));
var costume_color = costume_color_dim.group();
dc.pieChart('#costume-color')
.width(500)
.height(500)
.radius(500)
.innerRadius(100)
.slicesCap([7])
.transitionDuration(1500)
.dimension(costume_color_dim)
.group(costume_color);
}
CSV data comes in the below format
ID,name,Gender,Eye color,Race,Hair color,Publisher,Alignment,Superpower,Superpower Strength Level,Costume
Colour
0,A-Bomb,Male,Yellow,Human,No Hair,Marvel Comics,Good,Superhuman
Strength,10,None
1,Abin Sur,Male,Blue,Ungaran,No Hair,DC Comics,Good,Cosmic Power,40,Green
Yes, of course. Everything is specified dynamically in dc.js.
Assuming you are using dc.js v3 (and d3 v4+) the way I would suggest doing this is by creating another CSV file with the color assignments you want, something like
Name, RGB
Red, #ff1122
Blue, #1133ff
...
Then you can load the second file in parallel with your data using Promise.all(),
Promise.all([d3.csv('data.csv'), d3.csv('colors.csv')])
.then(function(data, colors) {
// rest of code will go here
});
ordinalColors is a nice convenience method, but if you want complete control, and to understand exactly what's going on, it's better to supply your own color scale. In this case, we want an ordinal scale, which maps specific discrete values to specific colors.
Under the covers, dc.js always deals with colors by using the colorAccessor to fetch a value for the the item, and then mapping this value using a color scale. You can think of the value that the accessor returns as a "color name", which is pretty convenient because it's exactly what you want here.
So you can populate a d3.scaleOrdinal with the domain of color names and the range of RGB colors:
var colorScale = d3.scaleOrdinal()
.domain(colors.map(row => row.Name))
.range(colors.map(row => row.RGB));
Now supply it to your chart using .colors():
chart.colors(colorScale);
What's really handy about this approach is that you can supply the same color scale for multiple charts, in order to make sure they are consistent. This is something that you don't get automatically in dc.js, because charts don't know very much about each other.
So, I managed to figure it out through an extensive period of trial and error and now I'm off and away with my dashboard. Thanks for your help, Gordon - it really made the difference! It needs a bit of tidying up but my working test code is below.
// Bring in data from both csv files
Promise.all([d3.csv("../data/heroes_information.csv"),
d3.csv("../data/costume_colors.csv")])
.then(function(data) {
// Tidy up data before use
data.forEach(function(d) {
d.Height = +d.Height;
d.Weight = +d.Weight;
d.Strength = +d.Strength;
});
// Bring in colorScale to dynamically color pie chart slices
var ndxcol = crossfilter(data[1]);
var colorScale = d3.scaleOrdinal()
.domain(data[1].map(row => row.Name))
.range(data[1].map(row => row.RGB));
// Bring in superhero data
var ndx = crossfilter(data[0]);
// Define chart types
var publisherSelector = dc.selectMenu('#publisher-selector')
var genderChart = dc.rowChart('#gender-balance');
// Define chart dimensions
var publisherChoice = ndx.dimension(dc.pluck('Publisher'));
var genderBalance = ndx.dimension(dc.pluck('Gender'));
// Define chart groups
var genderNumber = genderBalance.group();
var publisherNumber = publisherChoice.group();
// Draw charts
publisherSelector
.dimension(publisherChoice)
.group(publisherNumber);
genderChart
.width(500)
.height(200)
.margins({ top: 30, right: 30, bottom: 30, left: 30 })
.dimension(genderBalance)
.group(genderNumber)
.gap(6)
.colors(colorScale)
.transitionDuration(500)
.x(d3.scaleOrdinal())
.elasticX(true);
dc.renderAll();
});
I have a line chart and data in the form
[{
time: "2016-4-29"
total: 23242
},
{
time: "2016-5-16
total: 3322
}
...
]
I'm trying to filter on the x-axis with the brush, however, since I don't have every single date, if I brush in a small range, the filter handler seems to return an empty array for my filters
I've set up my line chart's x-axis like so:
.x(d3.time.scale().domain([minDate,maxDate]))
is there a way to make it so a user can only filter on dates that are in the dataset?
I would like the brush to snap to dates in the dataset.
it seems like whats happening is that you are able to brush between ticks..so it doesn't know what it selected.
I'm going to answer the easier question: How do I create a brush that will not allow nothing to be selected?
In other words, if the brush contains no data, do not allow it to take.
There are two parts to the solution. First, since any chart with a brush will remove the old filter and then add the new filter, we can set up the addFilterHandler to reject any filter that does not contain non-zero bins:
spendHistChart.addFilterHandler(function(filters, filter) {
var binsIn = spendHistChart.group().all().filter(function(kv) {
return filter.isFiltered(kv.key) && kv.value;
});
console.log('non-empty bins in range', binsIn.length);
return binsIn.length ? [filter] : [];
});
That's the straightforward part, and incidentally I think you could probably modify it to snap the brush to existing data. (I haven't tried it, though.)
The more tricky part is that this won't get rid of the brush, it just doesn't apply the filter. So the chart will end up in an inconsistent state.
We need to detect when the brush action has finished, and if there is no filter at that point, explicitly tell the chart to clear the filter:
spendHistChart.brush().on('brushend.no-empty', function() {
if(!spendHistChart.filters().length)
window.setTimeout(function() {
spendHistChart.filterAll().redraw();
}, 100);
});
We need a brief delay here, because if we respond to brushend synchronously, the chart may still be responding to it, causing bickering and dissatisfaction.
As a bonus, you get kind of a "nah-ah" animation because of the unintentional remove-brush animation.
demo fiddle
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
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
I am using Google Visualization Bar Chart and I would like to customize or change the tooltip text and format that appears when clicking on a bar.
I have been through documentation but I didn't find a way to implement
this. Do you know:
Is it even possible?
If so, could you provide some code examples ?
You can change the way the number is formatted by using the google.visualization.NumberFormat class.
var formatter = new google.visualization.NumberFormat({
fractionDigits: 0,
prefix: '$'
});
formatter.format(data, 1); // Apply formatter to second column.
If you need more flexibility, have a look at the PatternFormat class.
Here's the API reference.
Create a new data type for what you want in the tool tip:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Game');
data.addColumn('number', 'Transactions');
data.addColumn({type:'string', role:'tooltip'}); // here is the tooltip line
Now add the info that you want in your tooltip to you data:
['$FormatedWeekday', $SalesAll,'$ToolTip']
['$FormatedWeekday', $SalesAll,'$ToolTip']
['$FormatedWeekday', $SalesAll,'$ToolTip']
You will loose all the default data in your toll tip so you might want you re-package it:
$ToolTip = ''.$FormatedWeekday.' \u000D\u000A '.$SalesAll.' \u000D\u000A '."Red Cross Event";
the "\u000D\u000A" forces a line break
I was trying to do a similar thing with a Google pie chart. With the original code, on mouseover, the tooltip was showing the label, the raw number, and the percentage.
The orignal code was:
data.setValue(0, 0, 'Christmas trees');
data.setValue(0, 1, 410000000);
And the tooltip would show "Christmas trees 410000000 4.4%."
To format the text, I added a line to the code, so it was:
data.setValue(0, 0, 'Christmas trees');
data.setValue(0, 1, 410000000);
data.setFormattedValue(0, 1, "$410 million");
The result was a tooltip that read, "Christmas trees $410 million 4.4%"
I hope this helps!
Google Chart not support format html tooltip LineChart, BarChart.
I use:
google.visualization.events.addListener(chart, 'onmouseover', function(rowColumn){
myFunction();
});
in myFunction(): you can use popup to show more information.
There is a very easy way to do it, you just have to use one of the Formatters for the data:
// Set chart options
var options = {
hAxis: {format: 'MMM dd, y'}
};
// Format the data
var formatter = new google.visualization.DateFormat({pattern:'EEEE, MMMM d, y'});
formatter.format(data,0);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.AreaChart(document.getElementById('visualization'));
chart.draw(data, options);
You simply format the axis differently from data format, since the data format will only show up when you mouseOver.
Looks like you are now able to customize tooltip text by adding a special column that has role: 'tooltip': https://developers.google.com/chart/interactive/docs/customizing_tooltip_content
Another way to do it is by adding another column to your data that will act as the tooltip.
function drawVisualization() {
data = new google.visualization.DataTable()
data.addColumn('string', 'Date');
data.addColumn('number');
data.addColumn({type:'string',role:'tooltip'});
data.addRow();
base = 10;
data.setValue(0, 0, 'Datapoint1');
data.setValue(0, 1, base++);
data.setValue(0, 2, " This is my tooltip1 ");
data.addRow();
data.setValue(1, 0, 'Datapoint2');
data.setValue(1, 1, base++);
data.setValue(1, 2, "This is my second tooltip2");
// Draw the chart.
var chart = new google.visualization.BarChart(document.getElementById('visualization'));
chart.draw(data, {legend:'none', width:600, height:400});
}
FYI, All:
Google added custom HTML/CSS tooltips in September 2012:
https://google-developers.appspot.com/chart/interactive/docs/customizing_tooltip_content
I was also looking for the same option. Seems like there isn't any direct way. But we can disable the default tooltip and popup our own version using SelectHandler. Do let us know if you have figured out a more better/direct way. Thanks
The only way I found to disable it was to traverse the DOM in the hover handler (for pie charts anyway):
$(pie.Ac.firstElementChild.contentDocument.childNodes[0].childNodes[2].childNodes[1].firstChild.childNodes[2]).remove();
Which is hideous and subject to Google maintaining the structure that exists...
is there a better way?
Take a look at DataTable Roles and the tooltip example: https://developers.google.com/chart/interactive/docs/roles
label: 'Year', 'Sales', null, 'Expenses', null
`role: domain, data, tooltip, data, tooltip`
'2004', 1000, '1M$ sales, 400, '$0.4M expenses
in 2004' in 2004'
'2005', 1170, '1.17M$ sales, 460, '$0.46M expenses
in 2005' in 2005'
'2006', 660, '.66M$ sales, 1120, '$1.12M expenses
in 2006' in 2006'
'2007', 1030, '1.03M$ sales, 540, '$0.54M expenses
in 2007' in 2007'
The null labels are used as tooltip for 'Sales' and 'Expenses' respectively.