Create a Google Chart in javascript with JSON data - javascript

I need a column chart data with JSON, in order to automate this chart, but i dont no how do this.
So this is my JS Code:
function drawChart() {
const container = document.querySelector('#chart');
let chart = new google.visualization.ColumnChart(container);
//Informações data.json
let dataRequest = new Request("./datas/data.json");
fetch(dataRequest)
.then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data);
});
// Informações gráficos
let data = new google.visualization.arrayToDataTable([
["Volume", "Valor"],
["DA", 67],
["CIF", 23],
["Expurgo", 45]
]);
const options = {
titlePosition: 'none',
colors: ['#ed4a0e', '#15466e'],
backgroundColor: 'transparent',
animation: {
startup: true,
duration: 1000,
easing: 'out',
},
hAxis: { textStyle: { color: 'white' }, titleTextStyle: { color: 'white', fontSize: 15 } },
vAxis: { textStyle: { color: 'white' }, titleTextStyle: { color: 'white', fontSize: 15 } },
chartArea: { width: 250, height: 200 },
legend: {
textStyle: { color: '#ffffff', fontSize: 13 }
}
};
chart.draw(data, options)
};
My json:
[
["Volume", "Valor"],
["DA", 67],
["CIF", 23],
["Expurgo", 45]
]
I never do this before, and need a little help,if someone help whit this
(Sorry for my bad english)

Add "false" as last parameter
var data = google.visualization.arrayToDataTable([
["Volume", "Valor"],
["DA", 67],
["CIF", 23],
["Expurgo", 45]
],
false); // 'false' means that the first row contains labels, not data.

Related

Uncaught TypeError: getCharts is not a function or its return value is not iterable

I'm creating a React project that uses the React Google Charts library. Through an API call, I get information from the charts in an array and then loop through that array in a map to populate the object's charts property. However, when I call the method that performs this action, the end result of the map is a promise. I've already solved a similar situation working with the return of a component that was a list of options inside a select, but I'm not able to solve the problem of returning objects.
charts.js:
/* libraries */
import React from 'react';
import axios from 'axios';
/* stylesheets and assets */
import './../styles/global.css';
/* store */
import { GET_CHARTS } from './api-urls';
const getChartType = (chartType) => {
if (chartType === 'Coluna') {
return 'ColumnChart';
} else if (chartType === 'Barra') {
return 'BarChart';
} else if (chartType === 'Setor') {
return 'PieChart';
} else if (chartType === 'Linha') {
return 'LineChart';
} else { // default chartType
return 'ColumnChart';
}
}
const getCharts = async () => {
const response = await axios.get(GET_CHARTS);
const freeChartsArr = response.data.result.filter(chart => chart.exclusivo === 0);
const freeCharts = {
version: 1.0,
totalCharts: freeChartsArr.length,
charts: freeChartsArr.map(chart => {
return {
name: chart.descricaoGrafico,
chartType: getChartType(chart.tipoGrafico),
data: [
['Tempo', 'Despesas'],
[1, 113],
[2, 250],
[3, 500],
[4, 400]
],
options: {
colors: ['#2CE6A3', '#23B380', '#579C99'],
fontName: 'Roboto',
fontSize: 18,
titleTextStyle: {
marginBottom: 200,
fontSize: 24,
bold: true
},
legend: {
position: 'right',
alignment: 'center',
textStyle: {
color: '#818181',
fontSize: 16,
},
},
}
}
})
}
const premiumChartsArr = response.data.result.filter(chart => chart.exclusivo === 1);
const premiumCharts = {
version: 1.0,
totalCharts: premiumChartsArr.length,
charts: premiumChartsArr.map(chart => {
return {
name: chart.descricaoGrafico,
chartType: getChartType(chart.tipoGrafico),
data: [
['Tempo', 'Despesas'],
[1, 113],
[2, 250],
[3, 500],
[4, 400]
],
options: {
colors: ['#2CE6A3', '#23B380', '#579C99'],
fontName: 'Roboto',
fontSize: 18,
titleTextStyle: {
marginBottom: 200,
fontSize: 24,
bold: true
},
legend: {
position: 'right',
alignment: 'center',
textStyle: {
color: '#818181',
fontSize: 16,
},
},
}
}
})
}
return [freeCharts, premiumCharts]
}
console.log(getCharts()); // promises
const [freeCharts, premiumCharts] = getCharts();
export {
freeCharts,
premiumCharts
}
The exported variables are used in another file where I use the two chart objects to display them.

Javascript variable not working inside obejct . But getting on console.log

Javascript variable does not work inside an object. I see the data when I console.log(dataPondsRevenue) variable, but getting the error:
SyntaxError: missing ] after element list`!
when I use it inside the data:[] node:
$('.pondsRevenueBlock').on('click',function(){
var block_id = $(this).attr('data-id');
var url='{{ route('WhiteFish.client.pondsRevenueBlockWise') }}';
$.ajax({
url:url+'?block_id='+block_id,
}).done(function(pondsRevenueData){
var dataPondsRevenue = '';
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue+= '{value:'+element.pondTotalInvest+',name:'+element.name+'},';
});
console.log(dataPondsRevenue);
var eChart_2 = echarts.init(document.getElementById('pondsRevenue'));
var option1 = {
tooltip : {
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
axisPointer: {
type: 'cross',
label: {
backgroundColor: 'rgba(33,33,33,1)'
}
},
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
// color: ['#0FC5BB', '#92F2EF', '#D0F6F5'],
color: ['#0FC5BB', '#0FC5BB', '#5AC4CC'],
series : [
{
name: 'task',
type: 'pie',
radius : '55%',
center: ['50%', '50%'],
roseType : 'radius',
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)",
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
data:[
console.log(dataPondsRevenue);
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
eChart_2.setOption(option1);
eChart_2.resize();
}).fail(function (data) {
console.log('error');
});
});
How can I solve it?
Use an array (and optionally JSON.stringify it; in case of $.ajax, have a look at contentType at $.ajax docs), it is much less error-prone - in your case, there's always a trailing comma at the end, which is not a valid JSON:
console.log("Valid:")
console.log(JSON.parse('{ "whatever": 1 }'))
console.log("Invalid:")
console.log(JSON.parse('{ "whatever": 1, }'))
$('.pondsRevenueBlock').on('click',function(){
var block_id = $(this).attr('data-id');
var url='{{ route('WhiteFish.client.pondsRevenueBlockWise') }}';
$.ajax({
url:url+'?block_id='+block_id,
contentType: 'application/json'
}).done(function(pondsRevenueData){
var dataPondsRevenue = [];
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue.push({
value: element.pondTotalInvest,
name: element.name
})
});
console.log(dataPondsRevenue);
var eChart_2 = echarts.init(document.getElementById('pondsRevenue'));
var option1 = {
tooltip : {
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
axisPointer: {
type: 'cross',
label: {
backgroundColor: 'rgba(33,33,33,1)'
}
},
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
// color: ['#0FC5BB', '#92F2EF', '#D0F6F5'],
color: ['#0FC5BB', '#0FC5BB', '#5AC4CC'],
series : [
{
name: 'task',
type: 'pie',
radius : '55%',
center: ['50%', '50%'],
roseType : 'radius',
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)",
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
data: JSON.stringify(dataPondsRevenue),
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
eChart_2.setOption(option1);
eChart_2.resize();
}).fail(function (data) {
console.log('error');
});
});
Also, the console.log(), returns undefined - you can just pass the variable instead.
There seems to be quite a confusion as to how to create the needed data object. With the code
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue+= '{value:'+element.pondTotalInvest+',name:'+element.name+'},';
});
You are creating a JSON string. This could be parsed into an object using JSON.parse() but that seems unnecessary over complication as you could create the required array of objects to start with:
var dataPondsRevenue = [];
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue.push({value: element.pondTotalInvest, name: element.name});
});
Then, just assign dataPondsRevenue to data:
...
},
data: dataPondsRevenue,
itemStyle:
...
This is because console.log(dataPondsRevenue) is a function that returns undefined, so
data: [ console.log(dataPondsRevenue) ]
means
data: [ undefined ]
You should do
data: [ dataPondsRevenue ]
to get the actual data into the array.
You are creating a JSON string. This could be parsed into an object using JSON.parse() but that seems unnecessary over complication as you could create the required array of objects to start with:
var dataPondsRevenue = [];
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue.push({value: element.pondTotalInvest, name: element.name});
});

How to display a small bar even when a value is zero in Google Charts?

I have sometimes series where the values are all zero. When I apply a ColumnChart the figure is all empty, not showing that there are actually zero values.
How can I display the bars even when the values are zero?
I tried the following options:
{
type: options.type,
cssStyle: options.cssStyle,
data: {},
options: {
chartArea:{width:'80%'},
pointsVisible: true,
lineWidth: 4,
curveType: "none",
fontName: "Open Sans",
fontSize: 10,
colors: options.colors,
isStacked: "false",
fill: 10,
displayExactValues: true,
vAxis: {viewWindowMode:'explicit', minValue: -1, viewWindow: {min:0}, gridlines: {"color": "#f2f2f2", "count": 2}, baselineColor: "#f2f2f2", textStyle: options.textStyle},
hAxis: {gridlines: {"color": "#f2f2f2"}, baselineColor: "#f2f2f2", textStyle: options.textStyle},
legend: {position: 'bottom', alignment: 'center', textStyle: options.textStyle},
}
a bar will only be displayed if the value is not equal to zero
however, using object notation, we can provide the value (v:) and the formatted value (f:)
using the following, the bar will display, but when hovered, the tooltip shows a value of zero
{v: 0.1, f: '0'}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var data = google.visualization.arrayToDataTable([
['x', 'y'],
['A', {v: 0.1, f: '0'}],
['B', 2],
['C', 3],
['D', 4]
]);
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: 0, column: 1}]);
});
chart.draw(data, {
tooltip: {
trigger: 'both'
}
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
In your code, test for zero values and convert that to .1 or whatever is appropriate for your scale.
function vAxisTest (vAxis) {
let scale = .1; //
if(vAxis === 0) {
vAxis = scale;
return scale;
}
else { return vAxis; }
}

Apexchart: Multiple track Colors in Radialbar Chart Multiple

We are trying to make a design like each bar has unique track color instead of common colors in multiple bars, But i didnt find related help in documentation. Kindly someone help me to solve this.
Following is my working code,
var options = {
chart: {
height: 350,
type: 'radialBar',
},
plotOptions: {
radialBar: {
dataLabels: {
track: {
background: '#000000',
startAngle: -135,
endAngle: 135,
},
name: {
fontSize: '22px',
},
value: {
fontSize: '16px',
},
total: {
show: true
}
}
}
},
series: [44, 55, 67, 83],
labels: ['Apples', 'Oranges', 'Bananas', 'Berries'],
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
Thanks in advance,
Multiple track colors in radialBar are not implemented currently but will be available in v2.4.0
You will be able to do it like this
plotOptions: {
radialBar: {
track: {
background: ['#f3f3f3', '#e4e4e4']
}
}
}

How to change the horizontal axis color of a Column Chart?

I have got a Google Column Chart and I would like to change the color of its horizontal axis.
http://jsfiddle.net/chM9A/
function drawGenderColumnChart() {
var data = google.visualization.arrayToDataTable([
['Age', 'Female', 'Male'],
['13-17', 500, 600],
['18-24', 700, 800],
['25-34', 960, 950],
['35-44', 1030, 1100],
['44-54', 1030, 900],
['55-64', 950, 800],
['65+', 700, 500], ]);
var options = {
colors: ['#ADD6EA', '#DFB9D1'],
legend: {
position: 'none'
},
bar: {
groupWidth: "94%"
},
axisFontSize: 0,
vAxis: {
textPosition: 'none',
gridlines: {
color: 'transparent'
}
},
};
var chart = new google.visualization.ColumnChart(document.getElementById('age_chart'));
chart.draw(data, options);
}
I have been dissecting the documentation and it doesn't look like the API would let us do that. Do you have an idea?
use baselineColor:
vAxis: {
baselineColor:'Red',
textPosition: 'none',
gridlines: {
color: 'transparent'
}
}
http://jsfiddle.net/B4AfE/1/

Categories