Pass dynamic variables in options to Google Charts - javascript

I am trying to pass a Series number in a Google Chart option through a variable. However it is not accepting it as a variable and instead is taking it as a string. You can see in Image1 that I have passed in Series parameter SecondseriesColumnNumber as a variable and value is 1.
Image 1
However in the output it is considering it as a string but not as the series number as shown below
Image 2
Other parameters are considering the values correctly but not the series one. How can I make this work? My code is below
var options = {
title: title,
width: width,
height: height,
bar: { groupWidth: '75%' },
chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
backgroundColor: 'transparent',
tooltip: { textStyle: { color: 'black' }, isHtml: true },
isStacked: isStacked,
seriesType: seriesType,
series: { SecondseriesColumnNumber: { type: SecondseriesType } },
hAxis: { slantedText: true }
};
var chart = new google.visualization.ComboChart($('DivSeries')[0]);

the problem has to do with JavaScript syntax.
you are not able to use a variable as a key in the definition of an object.
you must first create the object, then you can add additional keys using variables.
there are two ways to get / set values of object keys, once the object is defined.
both of the following will return the same value for title.
var title = options.title;
var title = options['title'];
where as in the latter, we can substitute a variable for the title key.
var key = 'title';
var title = options[key];
in this case, define the static options as needed.
var options = {
title: title,
width: width,
height: height,
bar: { groupWidth: '75%' },
chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
backgroundColor: 'transparent',
tooltip: { textStyle: { color: 'black' }, isHtml: true },
isStacked: isStacked,
seriesType: seriesType,
series: {},
hAxis: { slantedText: true }
};
then you can use a variable to further define the series option.
var SecondseriesColumnNumber = 1;
options.series[SecondseriesColumnNumber] = { type: SecondseriesType };

Related

Specifying a width and height of 100% generates JavaScript errors

I am attempting to render a Google bar chart. In my JavaScript, I have the following:
var options = {
width: '100%',
height: '100%',
chartArea: {
height: '100%',
width: '100%',
left: 85,
top: 10,
bottom: 60,
right: 25
},
legend: { position: 'bottom', alignment: 'start' },
annotations: { alwaysOutside: true},
hAxis: {
gridlines: { count: 10 },
},
};
When I execute this, I get the following JavaScript errors:
However, if I change the height from '100%' to '400' as shown below, the chart renders correctly with no JS errors.
var options = {
width: '100%',
height: '400',
chartArea: {
height: '100%',
width: '100%',
left: 85,
top: 10,
bottom: 60,
right: 25
},
legend: { position: 'bottom', alignment: 'start' },
annotations: { alwaysOutside: true},
hAxis: {
gridlines: { count: 10 },
},
};
If it matters, the div that represents the chart is in a Bootstrap container. The HTML looks as follows:
<div id="chart_div" class="col-xs-12 col-md-6">
</div>
The issue is here that google chart width and height expect a number, but you are sending a string including the % symbol, this is what the NaN error is, its Not a Number!
EDIT
Apologies, the documents state it can be either a number or string, my guess is that it is trying to convert it to a string and the % causes the error
chartArea.width
Type: number or string
Default: auto
chartArea.height
Type: number or string
Default: auto
https://developers.google.com/chart/interactive/docs/gallery/barchart#configuration-options
Edit 2
I was actually looking at the chartArea.height and not height.
The documentation states that the height and weight should be in pixels, so a number
height
Height of the chart, in pixels.
Type: number
Default: height of the containing element
width
Width of the chart, in pixels.
Type: number
Default: width of the containing element
So I cant really answer your original question, why the chart will accept a string is a mystery, when it is clearly defined as requiring a number.

Render part of a large data set - dragToPan

I have 20000+ data points of the format [Date, Number], actual data is per hour for the last load of months.
I would like to show only the latest 28 days in the chart, but use the chart option explorer.actions: ['dragToPan', 'rightClickToReset'] to view data older than 28 days.
Basically, i want to show a subset of the data and then scroll to older data.
Is this even possible? Can someone provide an example of how its done?
google.charts.load('current', {
callback: function () {
var element = document.getElementById('#chart');
var data = google.visualization.arrayToDataTable([["Date","hits"],["2017-07-01",30],["2017-07-02",20],["2017-07-03",16],["2017-07-4",10],["2017-07-5",31],["2017-07-6",20],["2017-07-7",2],["2017-07-8",8],["2017-07-09",30],["2017-07-10",20],["2017-07-11",16],["2017-07-12",10],["2017-07-13",31],["2017-07-14",20],["2017-07-15",2],["2017-07-16",8]]);
var chart = new google.visualization.AreaChart(element);
var options = {
width: "100%",
height: "100%",
fontSize: 13,
animation: { duration: 1250, easing: 'out' },
legend: 'none',
chartArea: {
left: 40,
height: "80%",
width: "85%"
},
explorer: {
actions: ['dragToPan', 'rightClickToReset'],
axis: 'horizontal',
keepInBounds: false
},
hAxis: {
showTextEvery: 2,
textPosition: 'out',
format: 'dd MMM yy',
}
};
chart.draw(data, options);
},
packages:['corechart']
});
You can use hAxis.viewWindow.max and hAxis.viewWindow.max as per: https://developers.google.com/chart/interactive/docs/gallery/linechart
See: https://jsfiddle.net/5h7jxqq8/169/

Different tooltips for series in FlotChart

I have Flot line chart with two dataseries. I would like to edit the tooltips independently for each series. I have tried moving the tooltip settings to the dataset part but it didn't work.
Does anyone know a solution?
$(function () {
var barOptions = {
xaxis: {
tickDecimals: 0
},
yaxes: [{
position: "left"
}, {
position: "right"
}],
colors: ["#36c6d3"],
grid: {
color: "#888888"
},
tooltip: {
show: true,
content: "Uge %x, %s: %y"
}
};
var dataset = [{
data: occData.data,
label: occData.label,
yaxis: occData.yaxis,
lines: {
show: true,
lineWidth: 1,
}
}, {
data: houseData.data,
label: houseData.label,
yaxis: houseData.yaxis,
color: 'grey',
lines: {
show: true,
lineWidth: 1,
fill: false
}
}];
$("#flot-line-chart-past").plot(dataset, barOptions);
});
I'm going to presume that you are using flot.tooltip to provide the tooltips. In which case, the content property of the tooltip configuration object can be a function as well as a format string. I quote from the documentation for the plug-in:
you can pass a callback function(label, xval, yval, flotItem) that must return a string with the format described.
So write a function that distinguishes between each label you use for the two series, and return a different format string for each.

Update legend colors in ExtJS 6 chart

I have a bar chart with a legend in ExtJS 6.0.2.
I need to update the colors of the bars and of the legend when the user does an action (clicking on a pie slice in my case).
Updating the color of the bars works as intended, but the legend doesn't. Here is an example of what I do right now :
chart.getLegendStore().data.items.forEach(function(x){
x.data.mark = 'rgb(255,255,255)';
});
The colors are correctly set, but they only update when I click on the legend item. I guess it's because ExtJS has no way to know that the underlying store has been modified. I tried going up the callstack with the debugger but I didn't find anything useful.
Is there a better way to do what I want, or/and how to make the legend update instanly ?
EDIT: If it helps, here is how I update the bars :
serie.setConfig("colors", newColors);
EDIT2 : And here is the full chart code :
Ext.define('QuoteBarChart', {
extend: 'Ext.chart.CartesianChart',
alias: 'widget.quotebarchart',
xtype: 'quotebarchart',
requires: [
'Ext.chart.axis.Category',
'Ext.chart.axis.Numeric',
'Ext.chart.series.Bar',
'Ext.chart.series.Line',
'Ext.chart.theme.Muted',
'Ext.chart.interactions.ItemHighlight'
],
flex: 2,
height: 600,
theme: 'Muted',
itemId: 'chartId',
store: {
type: 'quote'
},
insetPadding: {
top: 40,
bottom: 40,
left: 20,
right: 40
},
axes: [{
type: 'numeric',
position: 'left',
fields: ['won', 'lost', 'open'],
minimum: 0,
grid: true,
titleMargin: 20,
title: 'Offres'
}, {
type: 'category',
position: 'bottom',
label: {
rotate: {
degrees: 45
}
},
fields: ['month']
}
],
series: [{
type: 'bar',
axis: 'left',
xField: 'month',
itemId: 'barId',
yField: ['open','lost','won'],
title: ['Ouvertes', 'Perdues','Gagnées'],
stacked: true,
fullStack: true,
colors: [
'rgb(64, 145, 186)', 'rgb(151, 65, 68)','rgb(140, 166, 64)'
],
highlight: {
strokeStyle: 'red',
fillStyle: 'black'
},
tooltip: {
trackMouse: true,
scope: this,
renderer: function (toolTip, storeItem, item) {
var name = "";
switch(item.field) {
case 'won': name = "Gagnées"; break;
case 'lost': name = "Perdues"; break;
case 'open': name = "Ouvertes"; break;
}
toolTip.setHtml("");
}
}
}],
legend: {
docked: 'bottom',
listeners: {
itemclick: 'onLegendItemClick',
itemmouseenter: 'onLegendItemHover'
}
}
)};
Ok, instead of modify colors of the series and colors of the legend, you can modify all of them in the same time doing this
chart.setColors(['red','blue','green']);
chart.redraw();
So you need to set colors on chart and not on series, and modify the array on button click.

Javascript: Object Model Dynamic Value at runtime

I wish to add an object model to a Google chart dynamically at runtime. I call a php function using AJAX to get the data and based on the number of columns, I wish to make the last column a line chart.
I wish to replace 5 by c as per below script.
c = data.getNumberOfColumns()-2
var options = {
width: 400,
height: 240,
seriesType: "bars",
series: {5: {type: "line"}},
};
c = data.getNumberOfColumns()-2;
var options = {
width: 400,
height: 240,
seriesType: "bars",
series: {}
};
options.series[c] = {type: "line"};

Categories

Resources