Cusomizing haxis label in google charts - javascript

I do have the following function to draw a chart, which represents some value for a given time. The horizontal axis should be the dates an not the numbers (which are important to make the trendline work). How can i achieved that?
chart_data contains of the following
[["Year","accept","error","total"],[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]]
The js function looks like this:
function drawChart(chart_id, chart_title, chart_data) {
var data = google.visualization.arrayToDataTable(
chart_data
);
var options = {
title: chart_title,
hAxis: {
title: 'Datum',
titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
trendlines: {
0: {
type: 'polynomial',
degree: 3,
},
1:{
type: 'polynomial',
degree: 3,
},
2:{
type: 'polynomial',
degree: 3,
} } // Draw a trendline for data series 0.
};
var chart = new google.visualization.AreaChart(document.getElementById(chart_id));
chart.draw(data, options);
}

to customize the haxis labels, use option hAxis.ticks
in this case, we can pull the first value from each row to use for our ticks
var chart_data = [
["Year","accept","error","total"],
[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],
[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],
[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]
];
// extract first value from each row
var ticks = chart_data.map(function (row) {
return row[0];
});
ticks.splice(0, 1); // remove column label
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chart_data = [
["Year","accept","error","total"],
[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],
[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],
[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]
];
// extract first value from each row
var ticks = chart_data.map(function (row) {
return row[0];
});
ticks.splice(0, 1); // remove column label
var data = google.visualization.arrayToDataTable(chart_data);
var options = {
title: 'chart_title',
hAxis: {
ticks: ticks, // custom labels
title: 'Datum',
titleTextStyle: {color: '#333'}
},
vAxis: {minValue: 0},
trendlines: {
0: {
type: 'polynomial',
degree: 3,
},
1:{
type: 'polynomial',
degree: 3,
},
2:{
type: 'polynomial',
degree: 3,
}
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Set colour of google bar chart via role:style

From a dynamically generate data array I am creating a DataTable and want to style it in a google charts as a bar chart.
I am going thru every data entry and creating a label and annotation.
But how do I give the column a certain colour?
I figured out that I need to use the role "style" but could not figure out the right syntax for the colour.
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols = [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: "stringify",
sourceColumn: i,
type: "string",
role: "annotation"
});
cols.push({
//the following options are not working...
role: "style: green"
'color: green'
color: "#109618"
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('PTCoverage'));
chart.draw(view, options);
use the calc function to return the value for the calculated column...
cols.push({
calc: function () {
return "green";
},
role: "style",
type: "string"
});
UPDATE
if the bars for every row in a specific column should be the same color,
don't need the 'style' column
use the colors configuration option instead
the colors option takes an array of colors,
one for each column / series
one series...
colors: ["green"]
two series...
colors: ["green", "red"]
etc...
EXAMPLE 1
using colors config option to apply colors to columns...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2'],
['Test 1', 500, 600, 1200],
['Test 2', 500, 600, 1200]
]);
var options = {
colors: ['green', 'red', 'blue']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EXAMPLE 2
use a 'style' column to change the colors for column / series 1...
(which basically overrides "green")
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0', {role: 'style', type: 'string'}, 'y1', 'y2'],
['Test 1', 500, 'cyan', 600, 1200],
['Test 2', 500, 'magenta', 600, 1200]
]);
var options = {
colors: ['green', 'red', 'blue']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I now managed to implement an array which returns a new color for evry bar, see below.
var colors = ['#66cc33','#3366CC','#DC3912','#FF9900','#DD4477','#994499','#0099C6','#109618'];
//...
cols.push({
sourceColumn: i,
calc: function () {
ccount++;
return colors[ccount];
},
role: "style",
type: "string"
});
//...
But this only adds the colors to the data in SR2, SR3 and SR4 have the colors as before, see pic (green color in the left chart, pink color in the midle and right for positive tested)
I think it might be because my data looks like this
var data = [
['Release', 'Test Case missing', 'negative tested', 'untested', 'partially tested','tested with restrictions','part tested with restrictions', 'positive tested'],
['SR2', MS2PTStatusMask.TCmissing,MS2PTStatusMask.NegTested,MS2PTStatusMask.UnTested,MS2PTStatusMask.RestTested,MS2PTStatusMask.PartTestWithRest,MS2PTStatusMask.PartTested,MS2PTStatusMask.PosTested],
['SR3', MS3PTStatusMask.TCmissing,MS3PTStatusMask.NegTested,MS3PTStatusMask.UnTested,MS3PTStatusMask.RestTested,MS3PTStatusMask.PartTestWithRest,MS3PTStatusMask.PartTested,MS3PTStatusMask.PosTested],
['SR4', MS4PTStatusMask.TCmissing,MS4PTStatusMask.NegTested,MS4PTStatusMask.UnTested,MS4PTStatusMask.RestTested,MS4PTStatusMask.PartTestWithRest,MS4PTStatusMask.PartTested,MS4PTStatusMask.PosTested],
]
How do I add the colors to the other bars?

google chart double axis, set format

I have created a Google bar chart, with two x-axis.
My problem is that I cannot seem to get the correct format on the bottom axis, which should be shown in percentage.
I have tried to use the following
axes:{{},{format:'#%'}}}
And in general inserting format:'#%' at places that would make sense, but nothing seems to work.
Is there anyone who has an idea for this?
See the entire code here: https://jsfiddle.net/laursen92/azr4kfn0/1/
google.charts.load('current', {
'packages': ['bar']
});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Slave number', 'Voltage', '%'],
['Slave 1', 12.15, 0.40],
['Slave 2', 12.18, 0.50],
['Slave 3', 11.80, 0.60],
['Slave 4', 13.12, 0.70],
]);
var formatter = new google.visualization.NumberFormat({
pattern: '##0.00'
});
var formatter2 = new google.visualization.NumberFormat({
pattern: '##0%'
});
formatter.format(data, 1);
formatter2.format(data, 2);
var options = {
width: 800,
chart: {
title: 'Status of slaves',
subtitle: 'Overview of the voltage and SOC of connected slaves. '
},
bars: 'horizontal', // Required for Material Bar Charts.
series: {
0: {
axis: 'voltage'
}, // Bind series 0 to an axis named 'voltage'.
1: {
axis: 'percent'
} // Bind series 1 to an axis named 'soc'.
},
axes: {
x: {
voltage: {
side: 'top',
label: 'Voltage'
}, // Top x-axis.
percent: {
label: 'Percent',
} // Bottom x-axis.
}
},
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
Here's an update to your fidde: https://jsfiddle.net/Balrog30/azr4kfn0/4/
I used the a little codepen I wrote to reverse-engineer the changes to the material chart options, which are still mostly undocumented. You can find that here: http://codepen.io/nbering/pen/Kddvge
Here's how the option should be formatted:
var options = {
axes: {
x: {
yourAxis: {
format: {
pattern: "#%"
}
}
}
};
-- Or --
options.axes.x.yourAxis.format.pattern = "#%";

Handling null data on Google Charts

I'm trying to create compound chart with a given data, that is, [date, value1, value2], however I can not handle such inputs:
// [["Day","Dose","INR"],["17/04",1.5,null]]
// [["Day","Dose","INR"]]
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,null]]
that is, when there are a set of data with a particular value all consist of nulls, I can not draw it on graph. Such inputs are fine:
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,0.9]]
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,0.9],["19/04",null,1.4]]
And here is my javascript code drawing the graph. Data is coming from a Ruby model.
$(function () {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable(<%= DrugInr.generate_array(#patient) %>);
var options = {
vAxes: { 1: {title: 'Dose', format: '#.#', maxValue: 20},
0: {title: 'INR',format: '#.#', minValue: -1, baselineColor:"#CCCCCC"} },
hAxis: {title: 'Day'},
seriesType: 'bars',
bar: {
groupWidth: 2
},
series: {
0:{ type: "bars", targetAxisIndex: 1 },
1:{ type: 'line', targetAxisIndex: 0}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
How can I handle these half empty values?
I would recommend the interpolateNulls option. See the ComboChart Configuration Options documentation for details.
var options = {
interpolateNulls: true
};
This option just tells the chart to guess what your values are if there's a null, rather than leave a gap. Works for most cases, anyway.
I solved this creating my data table like this:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'INR');
data.addColumn('number', 'Dosage');
data.addRows(<%= DrugInr.generate_array(#patient) %>);
var options = {
vAxes: { 1: {title: 'Dose', format: '#.#', maxValue: 20},
0: {title: 'INR',format: '#.#', minValue: -1, baselineColor:"#CCCCCC"} },
hAxis: {title: 'Day'},
seriesType: 'bars',
bar: {
groupWidth: 5
},
series: {
0:{ type: "bars", targetAxisIndex: 1 },
1:{ type: 'line', targetAxisIndex: 0}
}
};

How to make bars of different color in google charts?

I have the following code which generates a column chart.
<script type="text/javascript">
//google.charts.load('current', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Number of Visits', 'Average Check Size',{ role: 'style' }],
['8+', 26.22, '#083874'],
['4-7', 30.34,'#94CAFC'],
['2-3', 24.09,'#EBBA25'],
['1', 27.95,'#F59E47']
]);
var formatter = new google.visualization.NumberFormat({
fractionDigits: 1,
prefix: '$'
});
formatter.format(data, 1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" }]);
var options = {
//chartArea: {width: '50%'},
hAxis: {
title: 'Average Check Size',
titleTextStyle: {italic: false},
minValue: 0,gridlines: { color: 'transparent'}
},
vAxis: {
minValue: 0,
title: 'Number of Visits',
titleTextStyle: {italic: false},
gridlines: { color: 'transparent'}},
//colors: ['red','green','blue','yellow'],
legend: {position: 'none'},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_bar'));
chart.draw(view, options);
}
The output is a column chart with annotations on each of the bars. I want to have a similar kind of output but all four bars must have different colors. How do I do that? Please suggest
You can use the style role. There are examples on google charts page. And here is a jsfiddle.
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333'], // RGB value
['Silver', 10.49, 'silver'], // English color name
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
]);

Highstock, Dynamically add Points, a definied time span at the beginning

I have the following issue:
I want to dynamically update a hightstock Chart with Points from Ajax Calls. For Example i use setInterval(addPoints,3000); How can i develope the code, that the highstock Charts display an definied time, e.g. 1 Minute, and the Chart beginn to draw from the Left without this "time poping and squeezing? For a testrun i tried to you predifned null points, but the interval is not fix.
var value1="valueNo1";
var value2="valueNo2";
var color1="green";
var color2="red";
$(function () {
$('#container').highcharts('StockChart',{
chart: {
type: 'spline',
zoomtype: 'z'
},
title: {
text: 'Live random data'
},
navigator: {
top: 500
},
legend: {
enabled: true
},
rangeSelector: {
buttons: [{
count: 30,
type: 'second',
text: '30s'
}, {
count: 1,
type: 'minute',
text: '1M'
}, {
count: 2,
type: 'minute',
text: '2M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 1
},
xAxis: {
type: 'datetime'
}
});
});
var chart = $('#container').highcharts();
var ct = (new Date()).getTime();
// addAxis
chart.addAxis({ labels: { format: '{value}' , style: {color: color1 } }, title: { text: value1 , style: {color: color1} } , lineColor: color1, lineWidth: 0, opposite:true } );
chart.addAxis({ labels: { format: '{value}', style: {color: color2 } }, title: { text: value2 , style: {color: color2} } , lineColor: color2, lineWidth: 0 } );
// addSeries
chart.addSeries({ "name": "value1","data": [], yAxis: 2, marker: {enabled:true, radius: 5 }});
// addPoint
var current_time = (new Date()).getTime();
chart.series[0].addPoint([current_time+64000, null], false);
addPoints = function(){
var current_time = (new Date()).getTime();
chart.series[0].addPoint([current_time, Math.random()*10], false);
chart.redraw();
}
setInterval(addPoints,3000);
Please see jsFiddle demo of the issue :
http://jsfiddle.net/ehonk/FLzRH/1/
Please help
The "popping" is the data being added and the line connecting the last point to the new point and the yAxis re-scaling. To minimize this I would set the yAxis.max to a value that is the maximum possible. Secondly I would look at the animation and see which kind you want to use when it adds a new point.
To handle the "sqeezing" you can set your "viewable" range and your adding of points such that when you add a new point the last point on the left falls out of the viewable area.
You can also call setExtremes to set range on the xAxis.

Categories

Resources