Related
I'm a newbie in javascript and am trying to use googlecharts.
Now I have a problem about source column.
Now I can hide some column I need but when I toggle between hide and show the sourcecolumn is not showing anymore.
<html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var view = new google.visualization.DataView(data);
view.setColumns([ 0,
1,{ calc: "stringify",sourceColumn: 1,type: "string",role: "annotation" },
2,{ calc: "stringify",sourceColumn: 2,type: "string",role: "annotation" }]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "/" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
console.log(view);
var columns = []; var series = {}; for (var i = 0; i < data.getNumberOfColumns(); i++) { columns.push(i); if (i > 0) {
series[i - 1] = {}; } }
google.visualization.events.addListener(chart, 'select', function () { var sel = chart.getSelection(); // if selection length is 0, we deselected an element if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row === null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
},
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
console.log(view);
chart.draw(view, options);
} } });
} </script> </head> <body> <div id="columnchart_values" style="width: 900px; height: 500px;"></div> </body> </html>
This is my SouceCode
- https://jsfiddle.net/vpz2a4nc/
Please help me.
you're using data to build the columns,
but using view for the initial draw.
data does not include the annotation columns, only view.
so the column indexes do not align when one is hidden.
an easy fix is to convert the view to a data table,
and replace data before drawing the first time.
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {calc: "stringify", sourceColumn: 1, type: "string", role: "annotation"},
2, {calc: "stringify", sourceColumn: 2, type: "string", role: "annotation"}
]);
data = view.toDataTable();
see following working snippet...
google.charts.load('current', {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {calc: "stringify", sourceColumn: 1, type: "string", role: "annotation"},
2, {calc: "stringify", sourceColumn: 2, type: "string", role: "annotation"}
]);
data = view.toDataTable();
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "/" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(data, options);
var columns = [];
var series = {};
for (var i = 0; i < data.getNumberOfColumns(); i++) {
columns.push(i);
if (i > 0) {
series[i - 1] = {};
}
}
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row === null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
},
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_values" style="width: 900px; height: 500px;"></div>
I want to create google chart into png but it is not working in chrome. Please provide me solution for this. I don't understand what is wrong with this code because this code is working properly in Firefox. Here is my code-
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
arrayData = [
["Element", "Percent", { role: "style" } ],
/*["Gross Margin", 5.94, "#00aeef"],
["Operating Margin", 10.49, "#00aeef"],
["Net Profit", 19.30, "#00aeef"],
["Before Interest and Tax Margin (EBIT)", 21.45, "color: #00aeef"]*/
]
function drawChart() {
//console.log(arrayData);
var data = google.visualization.arrayToDataTable(arrayData);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var options = {
title: "Profitability Indicators(%)",
width: 555,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
vAxis: {
baselineColor:'Black',
textPosition: 'none',
gridlines: {
color: 'transparent'
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
document.getElementById('columnchart_values').outerHTML = 'Printable version';
}
I am trying to create a dynamic bar chart in a MVC application in Visual Studio
<input type="button" value="Add Column" onclick="add('Work',20)" class="btn btn-default btn-sm" />
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
var myObj = { "Elicit": 16, "Design": 23, "Code": 17, "Test": 24, "Deploy": 20 };
var myJSON = JSON.stringify(myObj);
var obj2 = JSON.parse(myJSON);
var v1 = obj2.Elicit;
var v2 = obj2.Design;
var v3 = obj2.Code;
var v4 = obj2.Test;
var v5 = obj2.Deploy;
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawTrendlines);
function drawTrendlines() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Items');
data.addColumn('number', 'Sales');
data.addRows([
['Elicitation', v1],
['Design', v2],
['Code', v3],
['Test', v4],
['Deploy', v5],
]);
var options = {
title: 'Project Division',
trendlines: {
0: {type: 'linear', lineWidth: 5, opacity: .3},
1: { type: 'exponential', lineWidth: 10, opacity: .3 },
2: {type: 'curve', lineWidth: 10, opacity: .3}
},
hAxis: {
title: 'Time of Day'
},
vAxis: {
title: 'Rating (scale of 1-10)'
},
colors: ['#80ccff', '#85e085', '#ffb84d', '#b3b3ff', '#ffb3ff'],
backgroundColor: '#f1f2f7',
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
function add(name,val)
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Items');
data.addColumn('number', 'Sales');
data.addRows([
['Elicitation', v1],
['Design', v2],
['Code', v3],
['Test', v4],
['Deploy', v5],
[name, val]
]);
var options = {
title: 'Project Division',
trendlines: {
0: { type: 'linear', lineWidth: 5, opacity: .3 },
1: { type: 'exponential', lineWidth: 10, opacity: .3 },
2: { type: 'curve', lineWidth: 10, opacity: .3 }
},
hAxis: {
title: 'Time of Day'
},
vAxis: {
title: 'Rating (scale of 1-10)'
},
colors: ['#80ccff', '#85e085', '#ffb84d', '#b3b3ff', '#ffb3ff'],
backgroundColor: '#f1f2f7',
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
where I can add and remove data displayed in the bar chart. I tried multiple ways but none of them seem to work.
Finally what I was able to do was add one additional column using variable name and value. However, it is not practical to have preset constructors for lets say 1 additional column, 2 columns and so on. Furthermore this does not allow me to delete columns. What can I do to solve this?
i'm trying to use Google Chart API for building an Waterfall chart. I noticed that Candlestick/Waterfall charts are not supporting the annotations.
See this jsfiddle sample
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'MinimumLevel');
data.addColumn('number', 'MinimumLevel1');
data.addColumn('number', 'MaximumLevel');
data.addColumn('number', 'MaximumLevel1');
data.addColumn({type: 'number', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addColumn({type: 'number', role: 'annotation'});
data.addRow(['Category 1', 0 , 0, 5, 5, 5,'gray',5]);
data.addRow(['Category 2', 5 , 5, 10, 10, 10,'red',10]);
data.addRow(['Category 3', 10 , 10, 15, 15, 15,'blue',15]);
data.addRow(['Category 4', 15 , 15, 10, 10, 10,'yellow',10]);
data.addRow(['Category 5', 10 , 10, 5, 5, 5,'gray',5]);
var options = {
legend: 'none',
bar: { groupWidth: '60%' } // Remove space between bars.
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I would like to put the value of the 5th column at the top of every candlestick.
It should look like this :
Is there a way to do this?
Thanks
I add annotations to candlestick charts by adding annotations to a hidden scatter plot. You can set exactly where you want the annotations to sit by changing the plot.
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Low');
data.addColumn('number', 'Open');
data.addColumn('number', 'Close');
data.addColumn('number', 'High');
data.addColumn('number'); //scatter plot for annotations
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
var high, low, open, close = 160;
for (var i = 0; i < 10; i++) {
open = close;
close += ~~(Math.random() * 10) * Math.pow(-1, ~~(Math.random() * 2));
high = Math.max(open, close) + ~~(Math.random() * 10);
low = Math.min(open, close) - ~~(Math.random() * 10);
annotation = '$' + close;
annotation_text = 'Close price: $' + close;
data.addRow([new Date(2014, 0, i + 1), low, open, close, high, high, annotation, annotation_text]);
}
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
chart.draw(view, {
height: 400,
width: 600,
explorer: {},
chartArea: {
left: '7%',
width: '70%'
},
series: {
0: {
color: 'black',
type: 'candlesticks',
},
1: {
type: 'scatter',
pointSize: 0,
targetAxisIndex: 0,
},
},
candlestick: {
color: '#a52714',
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
},
});
}
<script type="text/javascript"src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
just so happens, i ran into the same problem this week
so I added my own annotations, during the 'animationfinish' event
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var dataChart = new google.visualization.DataTable({"cols":[{"label":"Category","type":"string"},{"label":"Bottom 1","type":"number"},{"label":"Bottom 2","type":"number"},{"label":"Top 1","type":"number"},{"label":"Top 2","type":"number"},{"role":"style","type":"string","p":{"role":"style"}}],"rows":[{"c":[{"v":"Budget"},{"v":0},{"v":0},{"v":22707893.613},{"v":22707893.613},{"v":"#007fff"}]},{"c":[{"v":"Contract Labor"},{"v":22707893.613},{"v":22707893.613},{"v":22534350.429},{"v":22534350.429},{"v":"#1e8449"}]},{"c":[{"v":"Contract Non Labor"},{"v":22534350.429},{"v":22534350.429},{"v":22930956.493},{"v":22930956.493},{"v":"#922b21"}]},{"c":[{"v":"Materials and Equipment"},{"v":22930956.493},{"v":22930956.493},{"v":22800059.612},{"v":22800059.612},{"v":"#1e8449"}]},{"c":[{"v":"Other"},{"v":22800059.612},{"v":22800059.612},{"v":21993391.103},{"v":21993391.103},{"v":"#1e8449"}]},{"c":[{"v":"Labor"},{"v":21993391.103},{"v":21993391.103},{"v":21546003.177999996},{"v":21546003.177999996},{"v":"#1e8449"}]},{"c":[{"v":"Travel"},{"v":21546003.177999996},{"v":21546003.177999996},{"v":21533258.930999994},{"v":21533258.930999994},{"v":"#1e8449"}]},{"c":[{"v":"Training"},{"v":21533258.930999994},{"v":21533258.930999994},{"v":21550964.529999994},{"v":21550964.529999994},{"v":"#922b21"}]},{"c":[{"v":"Actual"},{"v":0},{"v":0},{"v":21550964.52999999},{"v":21550964.52999999},{"v":"#007fff"}]}]});
var waterFallChart = new google.visualization.ChartWrapper({
chartType: 'CandlestickChart',
containerId: 'chart_div',
dataTable: dataChart,
options: {
animation: {
duration: 1500,
easing: 'inAndOut',
startup: true
},
backgroundColor: 'transparent',
bar: {
groupWidth: '85%'
},
chartArea: {
backgroundColor: 'transparent',
height: 210,
left: 60,
top: 24,
width: '100%'
},
hAxis: {
slantedText: false,
textStyle: {
color: '#616161',
fontSize: 9
}
},
height: 272,
legend: 'none',
tooltip: {
isHtml: true,
trigger: 'both'
},
vAxis: {
format: 'short',
gridlines: {
count: -1
},
textStyle: {
color: '#616161'
},
viewWindow: {
max: 24000000,
min: 16000000
}
},
width: '100%'
}
});
google.visualization.events.addOneTimeListener(waterFallChart, 'ready', function () {
google.visualization.events.addListener(waterFallChart.getChart(), 'animationfinish', function () {
var annotation;
var chartLayout;
var container;
var numberFormatShort;
var positionY;
var positionX;
var rowBalance;
var rowBottom;
var rowFormattedValue;
var rowIndex;
var rowTop;
var rowValue;
var rowWidth;
container = document.getElementById(waterFallChart.getContainerId());
chartLayout = waterFallChart.getChart().getChartLayoutInterface();
numberFormatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
rowIndex = 0;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(rect) {
switch (rect.getAttribute('fill')) {
// use colors to identify bars
case '#922b21':
case '#1e8449':
case '#007fff':
rowWidth = parseFloat(rect.getAttribute('width'));
if (rowWidth > 2) {
rowBottom = waterFallChart.getDataTable().getValue(rowIndex, 1);
rowTop = waterFallChart.getDataTable().getValue(rowIndex, 3);
rowValue = rowTop - rowBottom;
rowBalance = Math.max(rowBottom, rowTop);
positionY = chartLayout.getYLocation(rowBalance) - 6;
positionX = parseFloat(rect.getAttribute('x'));
rowFormattedValue = numberFormatShort.formatValue(rowValue);
if (rowValue < 0) {
rowFormattedValue = rowFormattedValue.replace('-', '');
rowFormattedValue = '(' + rowFormattedValue + ')';
}
annotation = container.getElementsByTagName('svg')[0].appendChild(container.getElementsByTagName('text')[0].cloneNode(true));
$(annotation).text(rowFormattedValue);
annotation.setAttribute('x', (positionX + (rowWidth / 2)));
annotation.setAttribute('y', positionY);
annotation.setAttribute('font-weight', 'bold');
rowIndex++;
}
break;
}
});
});
});
$(window).resize(function() {
waterFallChart.draw();
});
waterFallChart.draw();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I am trying to change my Google Chart Tooltip, but it doesn't work. According to the Google, I should have to put:
data.addColumn({ type: 'string', role: 'tooltip' });
and
tooltip: { isHtml: true },
But doesn't work. I am just trying to put a phrase, instead, he puts a default value.
It is my code:
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Value');
**data.addColumn({ type: 'string', role: 'tooltip' });**
data.addColumn('number', 'Id');
for (i = 0; i < Object.keys(dataDB).length; i++) {
var year = dataDB[i].Year.toString();
var value = (dataDB[i].Value);
var message = "test";
var id = (dataDB[i].Id);
data.addRow([year, value, message, id]);
}
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var options = {
width: 1000,
height: 400,
focusTarget: 'category',
hAxis: { textPosition: 'none' },
legend: { position: 'none' },
chartArea: { left: 50, top: 30, width: "70%", height: "200%" },
bar: { groupWidth: "65%" },
tooltip: { isHtml: true },
};
var formatter = new google.visualization.NumberFormat({ decimalSymbol: ',', groupingSymbol: '.', negativeColor: 'red', negativeParens: true, prefix: 'R$ ' });
formatter.format(data, 1);
var chart = new google.visualization.BarChart(document.getElementById("divResult"));
chart.draw(view, options);
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length) {
var row = selection[0].row;
var _year = data.getValue(row, 0);
var _id = data.getValue(row, 3);
CallMensal(_id, _year);
}
});
}
also need to add column property
// col prop
data.addColumn({ type: 'string', role: 'tooltip', p: {html: true}});
EDIT
the column also needs to be included in the view which is used to draw the chart
include the column index when using view.setColumns
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);