I am trying to use secondary y axis with google charts.
I have this code:
arrdata.addRows([
[ObservationDateTime, observationValueCD4, observationValueViralLoad]
]);
}
// start of drawchart()
var options2 = {
title: 'CD4 && ViralLoad v/s DateTime',
vAxes: [{
title: 'CD4',
textStyle: {
color: 'blue'
}
}, // Axis 0
{
title: 'Viral Load',
textStyle: {
color: 'red'
}
} // Axis 1
],
hAxis: {
title: "Date"
},
series: {
0: {
type: "bars",
targetAxisIndex: 0
},
1: {
type: "line",
targetAxisIndex: 1
}
}
};
However, I am a bit confused with what is rendered:
It just renders blue straight vertical lines pointing up and no red line.Though secondary y axes in rendered.
What I expect: I expect blue bars for values on left y axis and red line for values on right y axes.
Without more code or sample data I can't say for sure what your issue is but your options seem to be correct for what you want.
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["ObservationDateTime", "observationValueCD4", "observationValueViralLoad"],
[new Date(2015,1,1), 9, 4],
[new Date(2015,2,1), 11, 6],
[new Date(2015,3,1), 20, 2],
[new Date(2015,4,1), 21, 3]
]);
var options2 = {
title: 'CD4 && ViralLoad v/s DateTime',
vAxes: [{
title: 'CD4',
textStyle: {
color: 'blue'
}
}, // Axis 0
{
title: 'Viral Load',
textStyle: {
color: 'red'
}
} // Axis 1
],
hAxis: {
title: "Date"
},
series: {
0: {
type: "bars",
targetAxisIndex: 0
},
1: {
type: "line",
targetAxisIndex: 1
}
}
};
var chart = new google.visualization.LineChart(document.getElementById("chart"));
chart.draw(data, options2);
}
// start of drawchart()
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart" style="width: 900px; height: 300px;"></div>
Related
I'm learning to work with Apexcharts and need to show the labels (Y axis labels an data labels) as currency (GBP) but can't seem to find the right approach. I have looked at the locale code, but really not sure how to integrate this into my chart.
I'm trying to ensure that 1000 become 1,000 etc.
Below is the chart code
<script>
var options = {
series: [
{
name: "Price in £s",
data: [1000, 2000, 2500, 3000, 4800, 6000]
}
],
chart: {
height: 350,
type: 'bar',
id: 'areachart-2',
dropShadow: {
enabled: true,
color: '#000',
top: 18,
left: 7,
blur: 10,
opacity: 0.2
},
toolbar: {
show: false
}
},
colors: ['#f6564d', '#545454'],
dataLabels: {
enabled: false,
textAnchor: 'middle',
formatter: function(val, index) {
return val.toFixed(0);
}
},
stroke: {
curve: 'straight'
},
title: {
text: '',
align: 'left'
},
grid: {
borderColor: '#f1f1f1',
row: {
colors: ['#fff', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
markers: {
size: 100
},
xaxis: {
categories: ['01/05/22','01/06/22','01/07/22','01/08/22','01/09/22','01/10/22'],
title: {
text: 'Month'
}
},
yaxis: {
min:00,
title: {
text: 'Price in GBP',
},
},
legend: {
position: 'top',
horizontalAlign: 'right',
floating: true,
offsetY: 100,
offsetX: 100
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
</script>
In yaxis add labels formatter
labels:{
formatter: (value) => {
return `${numberWithCommas(value)} GBP`;
},
},
And use this regex to add commas
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
Axes labels formatting can be controlled by yaxis.labels.formatter and xaxis.labels.formatter.
yaxis: {
labels: {
formatter: function (value) {
return value + "$";
}
},
},
xaxis: {
labels: {
formatter: function (value) {
return value;
}
}
}
I would like to increase the size of the following elements. Could you please edit the code below to make these elements bigger:
the label text size (the NaCl and SalinityDrift boxes above the
chart)
the numbers themselves in x,y,y2 axes
Script:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/1.1.1/chartjs-plugin-zoom.min.js"></script>
<canvas id="myChart"></canvas>
<script type="text/javascript">
$("#myChart").width( $(window).width() *0.97 );
$("#myChart").height( $(window).height() * 0.8 );
var ctx = document.getElementById('myChart').getContext('2d');
const options = {
type: 'line',
data: {
datasets: [
{
label: 'NaCl',
data: natriumChrolideData,
borderColor: 'blue',
yAxisID: 'y',
},
{
label: 'Salinity drift',
data: salinityDriftData,
borderColor: 'red',
yAxisID: 'y2',
},
]
},
options: {
parsing: false,
normalized: true,
animation: false,
responsive: false,
scales: {
x: {
type: 'time',
title: {
display: true,
text: 'Time (client time zone)',
font: {
size: 24
}
},
},
y: {
title: {
display: true,
text: 'NaCl storage, kg',
font: {
size: 24
}
}
},
y2: {
title: {
display: true,
text: 'Salinity drift, %',
font: {
size: 24
},
ticks: {
min: 0,
},
}
},
},
plugins: {
zoom: {
pan: {
enabled: true,
onPanStart({chart, point}) {
// alert("pan works!");
},
mode: 'x',
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true
},
mode: 'x',
}
}
},
}
}
new Chart(ctx, options);
</script>
Produced plot example:
Note: I found some solutions to use fontSize or tick.font or tick.fontSize, but either I implemented them wrongly or they do not work for some reason.
You are putting the ticks config in the scale title while its supposed to be on the root of the scale itself. Also for the boxes font size on top you need to configure it in the options.plugins.legend.labels namespace.
Live example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
legend: {
labels: {
font: {
size: 20
}
}
}
},
scales: {
x: {
ticks: {
font: {
size: 20
}
}
},
y: {
ticks: {
font: {
size: 20
}
}
}
}
}
}
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.1/chart.js"></script>
</body>
I've assigned three different colours to the labels, but the colour dots always show up as Blue, Green and Yellow. I'm pretty sure I've done something wrong.
The code I've written is:
var pieSimpleChart = {
chart: {
height: 350,
type: 'pie',
},
legend: {
position: 'bottom'
},
labels: ["IT", "Product Development", "Sales"],
series: [2, 2, 6],
fill: {
colors: ["#447b40", "#cc7870", "#e74ce4"]
}
}
var chart = new ApexCharts(document.querySelector("#task-pie-chart"), pieSimpleChart);
chart.render();
How can I match the labels to my selected colours?
I fixed it by removing "fill" option.
Now code looks like:
var pieSimpleChart =
{
chart:
{
height: 350,
type: 'pie',
},
legend:
{
position: 'bottom'
},
labels: ["IT", "Product Development", "Sales"],
series: [2, 2, 6],
colors: ["#447b40", "#cc7870", "#e74ce4"]
}
Use backgroundColor instead off fill: colors.
Also, you should use the dataset object for passing the values:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["IT", "Product Development", "Sales"],
datasets: [{
backgroundColor: [
"#ff0000",
"#00ff00",
"#0000ff"
],
data: [2, 2, 6]
}]
},
options: {
legend: {
position: 'bottom'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
I want to create a graph with the x-axis logarithmic. I took an example and changed the type to logarithmic. But I am getting all y values on the y-axis itself(see attached).But when I make y-axis logarithmic, It is works as expected. I am using chartjs version 2.9.3. When I used 2.8.0 there was no output.
This is my code:
<!doctype html>
<html>
<head>
<title>Logarithmic Line Chart</title>
<script src="/PHP/test/Chart.min.js"></script>
<script src="/PHP/test/utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
<button id="randomizeData">Randomize Data</button>
<script>
var randomScalingFactor = function() {
return Math.ceil(Math.random() * 10.0) * Math.pow(10, Math.ceil(Math.random() * 5));
};
var config = {
type: 'line',
data: {
labels: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
datasets: [{
label: 'My First dataset',
backgroundColor: window.chartColors.red,
borderColor: window.chartColors.red,
fill: false,
data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
},]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart - Logarithmic'
},
scales: {
xAxes: [{
stacked:false,
display: true,
type:'logarithmic',
}],
yAxes: [{
stacked:false,
display: true,
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById('canvas');
window.myLine = new Chart(ctx, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myLine.update();
});
</script>
</body>
</html>
If both axes are numeric the data needs to be provided as an array of points, i.e.:
[ { x: 111, y: 222 }, ... ]
From the documentation:
This alternate is used for sparse datasets, such as those in scatter charts. Each data point is specified using an object containing x and y properties.
Here's a working example from the posted code:
var config = {
type: 'line',
data: {
datasets: [{
label: 'My First dataset',
backgroundColor: 'red',
borderColor: 'red',
fill: false,
data: [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 4, y: 4 },
{ x: 5, y: 5 },
{ x: 6, y: 6 },
{ x: 7, y: 7 },
{ x: 8, y: 8 },
{ x: 9, y: 9 },
{ x: 10, y: 10 },
{ x: 11, y: 11 },
{ x: 12, y: 12 },
{ x: 13, y: 13 },
{ x: 14, y: 14 },
{ x: 15, y: 15 }
]
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart - Logarithmic'
},
scales: {
xAxes: [{
type: 'logarithmic'
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById('canvas');
window.myLine = new Chart(ctx, config);
};
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<canvas id="canvas"></canvas>
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>