The below code to generate google line chart works fine with 2 values (Date and Mean) assigned. When I added more data (including Mode and Variance as shown below), it just shows the original datas (Date and Mean). The other data are not displayed. What am I doing wrong here? please. I am still learning google charts. Any help would be appreciated greatly. thanks.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
);
}
$query = "SELECT Date, Mean, Mode, Variance FROM datatb";
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Multiple Data</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date','Mean','Mode','Variance'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date"]."', ".$row["Mean"].", ".$row["Mode"].", ".$row["Variance"]."],";
}
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var options = {
title: 'Data',
hAxis : {textStyle : {fontSize: 8}},
'tooltip' : { trigger: 'none'},
enableInteractivity: false,
width: '100%',
height: '700',
chartArea:{
left:10,
top: 100,
width: '100%',
height: '450',
},
pointSize:4,
vAxis: { textPosition: 'none', gridlines: { count: 10 }, baselineColor: 'gray' },
annotations: { stemColor: 'white', textStyle: { fontSize: 11 } },
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="curvechart" style="width: 2500px; height: 600px"></div>
</body>
</html>
Whitehat's suggestion:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
);
}
$query = "SELECT Date, Mean, Mode, Variance FROM datatb";
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Multiple Data</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('number', 'Mode');
data.addColumn('number', 'Variance');
var data = google.visualization.arrayToDataTable([
['Date','Mean','Mode','Variance'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date"]."', ".$row["Mean"].", ".$row["Mode"].", ".$row["Variance"]."],";
}
?>
]);
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'
}, 3, {
calc: 'stringify',
sourceColumn: 3,
type: 'string',
role: 'annotation'
}, ]);
var options = {
title: 'Data',
hAxis : {textStyle : {fontSize: 8}},
'tooltip' : { trigger: 'none'},
enableInteractivity: false,
width: '100%',
height: '700',
chartArea:{
left:10,
top: 100,
width: '100%',
height: '450',
},
pointSize:4,
vAxis: { textPosition: 'none', gridlines: { count: 10 }, baselineColor: 'gray' },
annotations: { stemColor: 'white', textStyle: { fontSize: 11 } },
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="curvechart" style="width: 2500px; height: 600px"></div>
</body>
</html>
after correcting the echo statement, just need to add column to the view...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, 3]);
or if you want all to have annotations...
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'
}, 3, {
calc: 'stringify',
sourceColumn: 3,
type: 'string',
role: 'annotation'
}, ]);
Related
Hello i am rendering these charts using chart js but i am unable to align these charts in the same order my config file and options file is given below
can anyone please help me with this. i tried with below options and data
const options = {
indexAxis: "y",
maintainAspectRatio: false,
aspectRatio: 0.8,
barThickness: 20,
responsive: true,
layout: {
padding: {
left: 1
}
},
plugins: {
legend: {
display: false
}
},
scales: {
x: {
ticks: {
color: "#495057"
},
grid: {
color: "#ebedef"
}
},
y: {
ticks: {
color: "#495057",
crossAlign: "near"
},
grid: {
color: "#ebedef"
},
gridLines: {
offsetGridLines: true,
display: true
}
}
}
};
const data = {
labels: ["red"],
datasets: [{
backgroundColor: "#42A5F5",
data: [65],
borderWidth: 2,
borderRadius: 75,
borderSkipped: false
},
{
backgroundColor: "#FFA726",
data: [28],
borderWidth: 2,
borderRadius: 50,
borderSkipped: false
}
]
};
how to align one below the other labels
As far as I know chart.js does not provide an option to set a minimum distance for the labels, a workaround to achieve this is to add spaces the the labels of the charts where the labels are shorter as the longest one so you will get something like this:
var options = {
type: 'bar',
data: {
labels: [" Red"],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: 'pink'
}]
},
options: {
indexAxis: 'y'
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
var options = {
type: 'bar',
data: {
labels: [" Red"],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: 'pink'
}]
},
options: {
indexAxis: 'y'
}
}
var options2 = {
type: 'bar',
data: {
labels: [" Yellowwwww"],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: 'pink'
}]
},
options: {
indexAxis: 'y'
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
var ctx2 = document.getElementById('chartJSContainer2').getContext('2d');
new Chart(ctx2, options2);
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<canvas id="chartJSContainer2" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
I am trying to display the total amount at the top of my chart.js; I'm trying to use the datalabel plugin but I'm not sure why it is not showing the labels, I don't get any errors, here's my code:
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels);
Chart.defaults.set('plugins.datalabels', {
color: '#FE777B'
});
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels],
data: {
datasets: [{
data: <?php print_r($barData); ?>,
label: 'Advisor Closed MTD',
backgroundColor: 'rgb(192,111,94)',
barThickness: 25,
datalabels: {
color: '#FFCE56'
}
}],
},
options: {
responsive: false,
plugins: {
datalabels: {
color: 'blue'
}
}
}
});
</script>
The chart shows the right information but the labels are not showing at all.
The labels are showing, they are in the bars itself, to show them on top of the bars you will need to configure it like so:
options: {
responsive: false,
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
labels: {
value: {
color: 'blue'
}
}
}
}
}
Example:
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels);
Chart.defaults.set('plugins.datalabels', {
color: '#FE777B'
});
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels],
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
data: [12, 19, 3, 5, 2, 3],
label: 'Advisor Closed MTD',
backgroundColor: 'rgb(192,111,94)',
barThickness: 25,
datalabels: {
color: '#FFCE56'
}
}],
},
options: {
responsive: false,
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
labels: {
value: {
color: 'blue'
}
}
}
}
}
});
</script>
I'm trying to have 2 pie charts and show in the legend only the inner labels.
The issues is that seems the labels color (in the legend) are taken from the the outer dataset, probably because it is the first.
How can I change it?
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['InnerLabel1','InnerLabebl2','InnerLabel3'],
datasets: [{
data: [1, 2, 1, 4],
backgroundColor: [
'rgba(31,119,180,0.5)','rgba(255,127,14,0.5)','rgba(255,127,14,0.5)','rgba(44,160,44,0.5)'
],
labels: [
'OuterLabel1','OuterLabel2','OuterLabel3','OuterLabel4'
]
}, {
data: [1, 3, 4],
backgroundColor: [
'#1f77b4','#ff7f0e','#2ca02c'
],
labels: ['InnerLabel1','InnerLabebl2','InnerLabel3'],
}, ]
},
options: {
responsive: true,
legend: {
display: true,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="myChart"></canvas>
You probably have to generate the legend labels yourself by defining a legend.labels.generateLabels function together with a legend.onClick that takes care of hiding and showing individual pie slices.
Here's an attempt of how this could be done.
const innerDataset = {
data: [1, 3, 4],
backgroundColor: ['#1f77b4', '#ff7f0e', '#2ca02c'],
labels: ['InnerLabel1', 'InnerLabebl2', 'InnerLabel3'],
};
var myChart = new Chart('myChart', {
type: 'pie',
data: {
datasets: [{
data: [1, 2, 1, 4],
backgroundColor: ['rgba(31,119,180,0.5)', 'rgba(255,127,14,0.5)', 'rgba(255,127,14,0.5)', 'rgba(44,160,44,0.5)'],
labels: ['OuterLabel1', 'OuterLabel2', 'OuterLabel3', 'OuterLabel4']
},
innerDataset
]
},
options: {
responsive: true,
legend: {
display: true,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
},
legend: {
labels: {
generateLabels: () => innerDataset.labels.map((label, i) => ({
text: label,
fillStyle: innerDataset.backgroundColor[i],
strokeStyle: '#fff',
hidden: myChart ? myChart.getDatasetMeta(1).data[i].hidden : false
}))
},
onClick: (event, legendItem) => {
const metaData = myChart.getDatasetMeta(1).data;
const iData = innerDataset.labels.indexOf(legendItem.text);
metaData[iData].hidden = !metaData[iData].hidden;
myChart.update();
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="myChart"></canvas>
I want the annotations above columns to always BE ABOVE columns. I set annotations.alwaysOutside to true, but whenever a column reaches the roof of the chart, it will position the annotation within the column. If you run the code on JSFiddle you'll see what I mean.
So, how can I force annotations to ALWAYS display above columns?
https://jsfiddle.net/y7ootfoo/
<link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<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([
["Mana Cost", "Cards"],
["0", 1],
["1", 2],
["2", 3],
["3", 4],
["4", 4],
["5", 3],
["6", 2],
["7+", 1],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation",
}, ]);
var options = {
title: "Cards/Mana Cost",
width: '750',
height: '375',
backgroundColor: "#FFF",
enableInteractivity: false,
bar: {
groupWidth: "90%"
},
legend: {
position: "none"
},
annotations: {
alwaysOutside: true,
stem: {
color: "transparent"
},
textStyle: {
fontName: 'Lato',
fontSize: 18.75,
bold: true,
italic: false,
auraColor: 'transparent',
color: "#000"
}
},
chartArea: {
backgroundColor: "#FFF"
},
titleTextStyle: {
color: "#000",
fontName: "Lato",
fontSize: 25,
bold: true,
italic: false
},
vAxis: {
gridlines: {
color: 'transparent'
},
textPosition: "none"
},
hAxis: {
textStyle: {
color: "#000",
fontName: "Lato",
fontSize: 18.75,
bold: true,
italic: false
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script>
<div id="columnchart_values" style="width: 900px; height: 300px;"></div>
set
var options = {
vAxis: {
viewWindow:{
max: maxV, //maximum value of annotations + 1
},
}}
I also add
chartArea: {
width: '95%',
}
https://jsfiddle.net/damiantt/y7ootfoo/1/
complete code:
<link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<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([
["Mana Cost", "Cards"],
["0", 1],
["1", 2],
["2", 3],
["3", 4],
["4", 4],
["5", 3],
["6", 2],
["7+", 1],
]);
var maxV = 0;
for (var i = 0; i < data.getNumberOfRows(); i++) {
if(data.getValue(i, 1) > maxV) {
maxV = data.getValue(i, 1);
}
}
maxV++;
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation",
}, ]);
var options = {
title: "Cards/Mana Cost",
width: '750',
height: '375',
backgroundColor: "#FFF",
enableInteractivity: false,
bar: {
groupWidth: "90%"
},
legend: {
position: "none"
},
annotations: {
alwaysOutside: true,
stem: {
color: "transparent"
},
textStyle: {
fontName: 'Lato',
fontSize: 18.75,
bold: true,
italic: false,
auraColor: 'transparent',
color: "#000"
}
},
chartArea: {
width: '95%',
backgroundColor: "#FFF"
},
titleTextStyle: {
color: "#000",
fontName: "Lato",
fontSize: 25,
bold: true,
italic: false
},
vAxis: {
viewWindow:{
max:maxV,
},
gridlines: {
color: 'transparent'
},
textPosition: "none"
},
hAxis: {
textStyle: {
color: "#000",
fontName: "Lato",
fontSize: 18.75,
bold: true,
italic: false
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script>
<div id="columnchart_values" style="width: 900px; height: 300px;"></div>
I'm using google visualization
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'time');
data2.addColumn('number', 'amount');
data2.addColumn({ type: 'string', role: 'tooltip' });
data2.addRows(rows_data);
var options2 = {
vAxis: { textPosition: 'none', title: '', textStyle: { fontName: 'arial'} },
hAxis: { slantedText: false, textStyle: { color: '#E6EFFA' }, gridlines: { color: '#E6EFFA', count: 20} },
backgroundColor: '#E6EFFA',
legend: 'none',
chartArea: { top: 0 },
colors: ['#435988'],
chartArea: { width: 800 }
};
chart2 = new google.visualization.LineChart(document.getElementById('chart_div_volume'));
I want the vAxis position to be on the right.
is it possible ?
Short Answer: Yes, but it's tricky.
Long Answer:
You need to set up a multi-axis chart. Basically, you create a dummy axis with no labels or anything to make it look like an axis. Then you configure a secondary axis. You create one set of dummy values (hidden) to put on the first axis, and plot your real data on the second.
Here is an example:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Dummy', 'Sales', 'Expenses'],
['2004', 0, 1000, 400],
['2005', null, 1170, 460],
['2006', null, 660, 1120],
['2007', null, 1030, 540]
]);
var options = {
title: 'Company Performance',
series: { 0: {targetAxisIndex: 0, visibleInLegend: false, pointSize: 0, lineWidth: 0},
1: {targetAxisIndex: 1},
2: {targetAxisIndex: 1}
},
vAxes: {
0: {textPosition: 'none'},
1: {},
}
};
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
chart.draw(data, options);
}
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Productivity');
data.addColumn('number', 'Composite');
data.addColumn({ type: 'number', role: 'annotation' });
data.addColumn('number', 'Average(N=5)');
var compositeDataArry = [];
compositeDataArry.push(["Ravi", 11, 11, 5]);
compositeDataArry.push(["Wasif", 5, 5, 5]);
compositeDataArry.push(["Vipin", 2, 2, 5]);
compositeDataArry.push(["Ankur", 3, 3, 5]);
compositeDataArry.push(["Pankaj", 1, 1, 5]);
compositeDataArry.push(["Dheeraj", 4, 4, 5]);
data.addRows(compositeDataArry);
var options = {
title: 'My Chart',
titleTextStyle: { color: '#264158', fontSize: 24 },
seriesType: 'bars',
annotations: {
alwaysOutside: true,
textStyle: {
color: '#000000',
fontSize: 15
}
},
hAxis: {
slantedText: true,
slantedTextAngle: -45
},
series: {
0: { targetAxisIndex: 0, },
1: { targetAxisIndex: 1, type: 'line' }
},
vAxes: {
0: { textPosition: 'none' },
1: {}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="chart_div" style="height: 500px; width: 100%"></div>
</body>
</html>