Related
I'm including multiple plots with Google Charts. I'd like to display one chart at a time but allow the user to switch between multiple csv input files. A change in input data would also require a change in chart and axis titles. I'm new to Javascript and I'm not sure how best to do this.
Here's how I'm currently plotting one csv. Any tips on how to toggle the change in input file would be appreciated. I'm currently using the jquery-csv module to read in my csv file into an array.
Script created in header.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Reading in a locally stored CSV file to an array of numbers
$.get("2017T.csv", function(csvString) {
var dataarray = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// Turning array into format usable by Google Charts
var data = google.visualization.arrayToDataTable(dataarray);
// Formatting Google Charts
var options = {
title: 'Raspberry PI Temperature plot - Yearly',
titleTextStyle: {
fontSize: '18',
},
vAxis: {
title: 'Temperature (\u00B0 C)' ,
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent'},
},
hAxis: {
title: 'Date',
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent'},
},
curveType: 'function',
backgroundColor: {
stroke: 'black',
strokeWidth: '5',
},
haxis: {
title: 'Hello',
},
legend: {position: 'none'},
};
//Creating Charts
var chart = new google.visualization.LineChart(document.getElementById('temp_year'));
chart.draw(data, options);
});
}
Chart called in body.
<div id="temp_year" style="width: 800px; height: 400px"></div>
You can accomplish this by making your drawChart function generic and then passing in the chart specific data each time you draw. This allows you redraw with new data and even makes it so it'll handle dynamic data too.
For example, based on your code you might do something like:
var chartData = {};
var dataarray;
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(function () {
drawChart(chartData);
});
// Reading in a locally stored CSV file to an array of numbers
$.get("2017T.csv", function (csvString) {
dataarray = $.csv.toArrays(csvString, { onParseValue: $.csv.hooks.castToScalar });
});
// Turning array into format usable by Google Charts
var data = google.visualization.arrayToDataTable(dataarray);
chartData = {
title: 'Raspberry PI Temperature plot - Yearly',
data: data
}
function drawChart(chartData) {
// Formatting Google Charts
var options = {
title: chartData.title,
titleTextStyle: {
fontSize: '18',
},
vAxis: {
title: 'Temperature (\u00B0 C)',
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent' },
},
hAxis: {
title: 'Date',
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent' },
},
curveType: 'function',
backgroundColor: {
stroke: 'black',
strokeWidth: '5',
},
haxis: {
title: 'Hello',
},
legend: { position: 'none' },
};
//Creating Charts
var chart = new google.visualization.LineChart(document.getElementById('temp_year'));
chart.draw(chartData.data, options);
}
So what I've done is created a chartData object that you can define any chart specific variables in. I've only done the title and data, but obviously you can do as many of the chart options as you want. Then, when you want to redraw the chart, you overwrite the chartData object with the new chart's data and call drawChart again with the new data.
I have created a Google Chart that visualises the outside temperature at my house. The amount of data keeps growing, so the chart gets unreadable in a few days ;-)
I want to be able to zoom in on the x-axis, but I can't get it to work with the explorer option.
I've tried:
explorer: { actions: ["dragToZoom", "rightClickToReset"],
maxZoomIn: 0.2,
maxZoomOut: 1.0,
zoomDelta: 10,
axis: "horizontal",
keepInBounds: true
},
But that doesn't seem to work.
Here's what I've got so far:
https://codepen.io/wtrdk/pen/wpGVVW or https://weather.wtrdk.nl/test.html
UPDATE:
I've added the following code to create a continuous axis, but I still can't zoom in...
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'datetime'
},
// just use index # for second column
1
]);
try using the current library...
<script src="https://www.gstatic.com/charts/loader.js"></script>
jsapi is out of date, according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
this will only change the load statement,
see following working snippet...
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
$.get(
"https://cors-anywhere.herokuapp.com/https://weather.wtrdk.nl/temperature.csv",
function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {
onParseValue: $.csv.hooks.castToScalar
});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'datetime'
},
// just use index # for second column
1
]);
var temperature = new google.visualization.ChartWrapper({
chartType: "AreaChart",
containerId: "temperature",
dataTable: view,
options: {
height: 400,
explorer: {
actions: ["dragToZoom", "rightClickToReset"],
//axis: "horizontal",
//keepInBounds: true
},
animation: { duration: 2000, easing: "out", startup: true },
title: "Temperature",
titleTextStyle: { color: "grey", fontSize: 11 },
legend: { textStyle: { color: "grey", fontSize: 11 } },
backgroundColor: { fill: "transparent" },
colors: ["#e39c3a"],
hAxis: {
textStyle: {
color: "grey",
fontSize: 11
},
//format: 'datetime',
},
vAxis: {
title: "°C",
titleTextStyle: {
color: "grey",
fontSize: 22
},
textStyle: {
color: "grey",
fontSize: 11
}
}
}
});
temperature.draw();
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://weather.wtrdk.nl/jquery.csv.min.js"></script>
<body bgcolor="#282B30">
<div id="temperature"></div>
</body>
I'm trying to color the bars in a Google Charts bar chart by their value. I know from the documentation that I can specify a style role to color specific bars a specific color, but I haven't been able to locate an example showing whether it's possible to color bars by their value.
I have created a fiddle demonstrating my chart structure. My data is a continuous series of integers.
var data = google.visualization.arrayToDataTable([
['Asset','Days in Stock'],
['4990/473',606],['4990/489',504],['4990/557',159],['4990/559',147],
['4990/578',87],['4990/581',63],['4990/582',53],['4990/586',41],
['4990/590',25],['4990/592',20],['4990/593',5],
]);
I haven't been able to determine from the documentation whether it's in fact possible to set threshold ranges for setting the bar colors. Ideally I'd want to be able to use a range formatter but it doesn't seem to work with the bar chart type.
var formatter = new google.visualization.TableColorFormat();
formatter.addRange(0, 60, 'green', '#00ff00');
formatter.format(data, 1);
https://jsfiddle.net/dL997yv6/
So if there is a way to do this using a format function that would be ideal, however if there isn't then I will settle for programmatically setting the color per bar using my data values in my scripting language.
the color formatter works on Table charts
to set the color of the bar by value, add a calculated column to the data view,
similar to the annotation column
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Asset','Days in Stock'],
['4990/473',606],['4990/489',504],['4990/557',159],['4990/559',147],
['4990/578',87],['4990/581',63],['4990/582',53],['4990/586',41],
['4990/590',25],['4990/592',20],['4990/593',5],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
// style column
{
calc: function (dt, row) {
if ((dt.getValue(row, 1) >= 0) && (dt.getValue(row, 1) <= 60)) {
return 'green';
} else if ((dt.getValue(row, 1) > 60) && (dt.getValue(row, 1) <= 100)) {
return 'yellow';
} else {
return 'red';
}
},
type: 'string',
role: 'style'
},
// annotation column
{
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}
]);
var options = {
title: '',
titleTextStyle: {
fontSize: 16,
bold: true
},
backgroundColor: 'transparent',
chartArea: {
left:80,
top:30,
bottom:60,
right:10
},
legend: {
textStyle: {
fontSize: 11
}
},
vAxis: {
title: 'Asset',
textStyle: {
fontName: 'Arial',
fontSize: 10
},
titleTextStyle: {
fontSize: 12,
italic: false,
bold:true
}
},
hAxis: {
title: 'Days in Stock',
gridlines: {
count: 22
},
textStyle: {
fontName: 'Arial',
fontSize: 11
},
titleTextStyle: {
fontSize: 12,
italic: false ,
bold:true
}
},
pointSize: 3,
pointShape: 'circle',
annotations: {
alwaysOutside: true,
textStyle: {
fontName: 'Arial',
fontSize: 9,
color: '#000000',
opacity: 1
}
}
};
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chartDiv);
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
My Chart has a datetime value and two number values (positive and negative).
The above image shows the results of drawing one bar, datetime being current date, the problem is, the bar covers 1990 to 2050, when it should only be covering the current month.
If I draw 2 bars, one for last month, and one for current month, everything is drawn properly.
I'm assuming GoogleCharts needs at least 2 dates for some reason. Does anyone have any idea how to fix this, or give some direction.
Thanks in advance,
Edit to ADD:
The Chart that I am using:
google.charts.load('current', {packages: ['corechart', 'controls']});
The single bar that I am drawing comes from this data store in historyChart:
[["2016-10-01T00:00:00+00:00", 5000.0, 0]]
I am inserting this data to the chart in this manner:
data.addColumn('datetime', 'Chart Filter');
data.addColumn('number');
data.addColumn('number');
data.addRows(historyChart);
The Chart wrapper and options are as followed:
var programmaticChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'programmatic_chart_div',
'options': {
displayExactValues:false,
vAxis: {
format: '$#,###', //add $sign in virtical axis
viewWindowMode: 'maximized',
},
hAxis:{
format: 'MMM-yyyy',
},
width: 900,
height: 450,
chartArea: {
'backgroundColor': {
'fill': '#F4F4F4',
'opacity': 100
},
top:50,
left:85,
width: 1000
},
title: "{{ member.username }}'s chart", //set user name as chart's title
isStacked:"true",
bar:{groupWidth: "95%"},
colors: ['#7FFF00', '#e6693e'],
}
});
// Create and draw the visualization.
dashboard.bind(programmaticSlider, programmaticChart);
dashboard.draw(data);
adding option for hAxis.ticks seems to help...
see following working snippet...
google.charts.load('43', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Chart Filter');
data.addColumn('number');
data.addColumn('number');
data.addRows([
[new Date("10/01/2016"), 5000.0, 0]
]);
var programmaticChart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'programmatic_chart_div',
dataTable: data,
options: {
displayExactValues: false,
vAxis: {
format: '$#,###',
viewWindowMode: 'maximized'
},
hAxis:{
format: 'MMM-yyyy',
ticks: [new Date("10/01/2016")]
},
width: 900,
height: 450,
chartArea: {
backgroundColor: {
fill: '#f4f4f4',
opacity: 100
},
top: 50,
left: 85,
width: 1000
},
title: '{{ member.username }}\'s chart',
isStacked: 'true',
bar:{groupWidth: '95%'},
colors: ['#7fff00', '#e6693e']
}
});
programmaticChart.draw();
//dashboard.bind(programmaticSlider, programmaticChart);
//dashboard.draw(data);
},
packages: ['corechart', 'controls']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="programmatic_chart_div"></div>
I tried multiple solutions given out from
How to set Axis step in Google Chart?, Trying to set y axis to 0 in google charts, and several other posts that I have looked over without any luck. Does anyone have an idea of what can be done in order to set the y axis to a starting point of 0? I can provide more information if need be. Also a side question, is it possible to bring a line to the front when clicked on. For example when you click on the current trend line, it bolds but the data points do not appear for them.
<div id="thelinechart" style="width: 1000px; height: 550px"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();data.addColumn('string','Year');
data.addColumn('number','Current Trend');
data.addColumn('number','2015 Projection');
data.addColumn('number','2016 Projection');
data.addColumn('number','2017 Projection');
data.addColumn('number','2018 Projection');
data.addRows([
['2015',250,250,null,null,null],['2016',200,300,200,null,null],['2017',200,310,230,200,null],['2018',290,340,320,280,290],['2019',null,370,350,360,290],['2020',null,null,430,470,390],['2021',null,null,null,520,440],['2022',null,null,null,null,450]
]);
var options = {
chart: {
title: 'Capacity',
subtitle: 'in weight'
},
width: 850,
height: 450,
vAxis: {
viewWindowMode: 'explicit',
viewWindow: {
//max: 8000,
min: 0,
},
gridlines: {
count: 18, //set kind of step (max-min)/count
}
}
};
var chart = new google.charts.Line(document.getElementById('thelinechart'));
chart.draw(data, options);
}
</script>
I have a jsfiddle link where I have my code.
https://jsfiddle.net/abufr36y/
Need to convert options for Material Charts, depending on the package...
google.charts.Line.convertOptions(options)
See following example...
google.charts.load('current', {
callback: drawChart,
packages: ['line']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string','Year');
data.addColumn('number','Current Trend');
data.addColumn('number','2015 Projection');
data.addColumn('number','2016 Projection');
data.addColumn('number','2017 Projection');
data.addColumn('number','2018 Projection');
data.addRows([
['2015',250,250,null,null,null],['2016',200,300,200,null,null],['2017',200,310,230,200,null],['2018',290,340,320,280,290],['2019',null,370,350,360,290],['2020',null,null,430,470,390],['2021',null,null,null,520,440],['2022',null,null,null,null,450]
]);
var options = {
chart: {
title: 'Capacity',
subtitle: 'in weight'
},
width: 850,
height: 450,
vAxis: {
viewWindowMode: 'explicit',
viewWindow: {
//max: 8000,
min: 0,
},
gridlines: {
count: 18, //set kind of step (max-min)/count
}
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 2, 3, 4, 5, 1]);
var chart = new google.charts.Line(document.getElementById('thelinechart'));
// convert options for Material Charts, use view vs. data
chart.draw(view, google.charts.Line.convertOptions(options));
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="thelinechart"></div>