Google Chart: How to draw the vertical axis for LineChart? - google-visualization

I want to draw a Google's line chart in my web page! Here is my js code:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['x', 'Cats', 'Blanket 1'],
['A', 1, 10],
['B', 2, 5],
['C', 4, 12],
['D', 8, 5]
]);
var options = {
curveType: 'function',
lineWidth: 2,
hAxis: {
baselineColor: 'red',
textStyle: {color: '#000', fontName: 'Arial', fontSize: 10},
gridlines: { color: '#f3f3f3', count: 5}
},
vAxis: {
baseline: 0,
viewWindowMode: "explicit",
viewWindow:{ min: 0 },
gridlines: { color: '#f3f3f3', count: 6}
}
};
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, options);
}
However, the result chart is drawing without any vertical axis line. How I can add the vertical axis lines as below images:
Thank you so much!

Gridlines are not supported for category axes. Because the data in question is using strings as the categories (X-axis labels), there is no way to tell how they "should" be split. You can get around this, however, with the following techniques.
Trick 1: Turn your Data Numerical
So right now you have strings which means no gridlines. We want gridlines though, so we have to correct that small problem. So we turn our first column (X) in to a number, with a format on it so it says 'A' or 'B' or 'C' when you mouse over it (and in the legend):
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
data.addRows([
[{v: 1, f:'A'}, 1, 10],
[{v: 2, f:'B'}, 2, 5],
[{v: 3, f:'C'}, 4, 12],
[{v: 4, f:'D'}, 8, 5]
]);
This doesn't solve the problem though. Now we have numbers on the bottom axis, cut off at weird 0.8 intervals. So we want to fix that. Unfortunately, with the hAxis, you can't set a min/max value and have it stick (I don't know why). We can fix the min by adding baseline: 0 to our options.
To get the max, we have to add a dummy series.
Put it all together, and we get this:
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
// This dummy series is to extend the chart from 0-5 for padding
data.addColumn('number', null);
data.addRows([
[{v: 1, f:'A'}, 1, 10, null],
[{v: 2, f:'B'}, 2, 5, null],
[{v: 3, f:'C'}, 4, 12, null],
[{v: 4, f:'D'}, 8, 5, null],
[{v: 5, f:''}, null, null, {v: 0, f:''}]
]);
options = {
curveType: 'function',
lineWidth: 2,
hAxis: {
// Show a baseline at 0
baseline: 0,
// 6 Gridlines, 4 labels + left and right for padding
gridlines: {
count: 6
},
},
vAxis: {
baseline: 0,
},
series: [
{},
{},
// Hide our dummy series
{
lineWidth: 0,
pointsize: 0,
visibleInLegend: false
},
]
};
chart1 = new google.visualization.LineChart(document.getElementById('visualization'));
chart1.draw(data, options);
}
Now it's looking more like what you want. There are two main issues. One is that if you mouseover the bottom right of the chart, a blank tooltip pops up (this is not a huge issue I'd hope, though you may have to do some error trapping if you make the chart interactive with events). The other is that the bottom of our chart is showing numbers, not letters.
Unfortunately, there is no easy way to format numbers as letters (at least until Google implements the entire ICU pattern set rather than just dates/numbers). So we need to make another workaround. Basically, what I do is create an entirely new chart just to make the labels. I then format it so that it hides everything but the labels, and make sure that it lines up horizontally with the chart above.
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
// This dummy series is to extend the chart from 0-5 for padding
data.addColumn('number', null);
data.addRows([
[{v: 1, f:'A'}, 1, 10, null],
[{v: 2, f:'B'}, 2, 5, null],
[{v: 3, f:'C'}, 4, 12, null],
[{v: 4, f:'D'}, 8, 5, null],
[{v: 5, f:''}, null, null, {v: 0, f:''}]
]);
options = {
curveType: 'function',
lineWidth: 2,
hAxis: {
// Show a baseline at 0
baseline: 0,
// 6 Gridlines, 4 labels + left and right for padding
gridlines: {
count: 6
},
// Hide our labels
textPosition: 'none'
},
vAxis: {
baseline: 0,
},
series: [
{},
{},
// Hide our dummy series
{
lineWidth: 0,
pointsize: 0,
visibleInLegend: false
},
]
};
// Add dummy data for the axis labels
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'x');
data2.addColumn('number', 'dummy');
data2.addRows([
['A', null],
['B', null],
['C', null],
['D', null]
]);
chart1 = new google.visualization.LineChart(document.getElementById('visualization'));
chart1.draw(data, options);
chart2 = new google.visualization.LineChart(document.getElementById('visualization2'));
chart2.draw(data2,
{
chartArea: {
top:0,
height:"0%"
},
min: 0,
max: 0,
hAxis: {
baselineColor: '#FFFFFF'
},
vAxis: {
baselineColor: '#FFFFFF',
direction: -1,
textPosition: 'none',
gridlines: {
color: '#FFFFFF'
}
}
});
}
Just make another below the first one, and use CSS to align it properly (float it around the same position, or whatnot), and it looks like the labels belong to the chart above.
It ain't glorious, but it works.

There is a more elegant solution by using xticks:
To do that we define a datatable like this:
var data = new google.visualization.DataTable();
data.addColumn('number', 'Month');
data.addColumn('number', 'Sales');
data.addRows([
[{v: 0, f:'Jan'}, 1000],
[{v: 1, f:'Feb'}, 1170],
[{v: 2, f:'Mar'}, 660],
[{v: 3, f:'Apr'}, 1030]
]);
Where we set number values but also string labels for the Month axis.
With just this and the format attribute removed, we would get vertical lines but numbers instead of the strings for the x axis labels, which is not what we want.
To fix this we can set xticks to force the correct labels in the plot.
var options = {
title: '',
hAxis: {
title: 'Month',
titleTextStyle: {
color: '#333'
},
baseline: 0,
gridlines: {
color: '#f3f3f3',
count: 4
},
ticks: [{v: 0, f:'Jan'},{v: 1, f:'Feb'},{v: 2, f:'Mar'},{v: 3, f:'Apr'}], // <------- This does the trick
},
vAxis: {
minValue: 0,
gridlines: {
color: '#f3f3f3',
count: 5
}
}
};
Hereby a complete working fiddle to show you how it can be done: http://jsfiddle.net/j29Pt/417/

Related

ChartJs line chart - display permanent icon above some data points with text on hover

I have a chart i need to draw that, in addition to the data points, i want an icon permanently above (some) data points with a custom text string.
I don't need the default value popover as i can make do with a custom legend, but i need to add an icon above one or two points, and on hover of the icon, display a popover. i need to build the popover text string from non-chart related data.
The custom data labels don't appear to be flexible enough to allow different icons/popovers on different data points, i may be wrong though.
Another possibility is chartjs-plugin-datalabels, but I'm not sure about that.
In case your chart (canvas) is of fixed size, you can easily solve this problem by adding an additional dataset that specifies nothing but the icons to be shown in the chart.
{
data: data2.map((v, i) => imageIndexes.includes(i) ? v + 1.2 : null),
fill: false,
pointStyle: icon,
pointRadius: 22,
pointHoverRadius: 22
}
Given the data array data2 and the array imageIndexes, the data of the icons dataset can be built using Array.map. Note that the values - where any - are derived from corresponding values in data2 but slightly increased to make the images appear on top of them.
data2.map((v, i) => imageIndexes.includes(i) ? v + 1.2 : null)
Further you'll need to define a tooltips object inside the chart options in order to style the popup and to make sure, tooltips are only displayed when the mouse hovers over the icons.
tooltips: {
filter: tooltipItem => tooltipItem.datasetIndex == 2,
titleFontSize: 16,
titleAlign: 'center',
callbacks: {
title: (tooltipItem) => tooltipItem.length == 0 ? null : tooltipText,
label: () => null
}
},
Please have a look at the runnable code snipped below.
const labels = ['A', 'B', 'C', 'D', 'E', 'F'];
const alerts = ['B', 'D'];
const data1 = [0, 2, 1, 3, 2, 1];
const data2 = [1, 3, 3, 4, 3, 2];
const imageIndexes = [1, 3];
const tooltipText = 'Efficiency of Standard Curve\nnot opimal';
var icon = new Image();
icon.src = 'https://i.stack.imgur.com/YvlWY.png';
const chart = new Chart(document.getElementById("myChart"), {
type: "line",
data: {
labels: labels,
datasets: [{
data: data1,
fill: false,
backgroundColor: 'blue',
borderColor: 'blue',
lineTension: 0,
pointRadius: 5,
pointHoverRadius: 5,
pointBorderWidth: 3,
pointHoverBorderWidth: 3,
pointBorderColor: 'white',
pointHoverBorderColor: 'white'
},
{
data: data2,
fill: false,
showLine: false,
backgroundColor: 'orange',
pointRadius: 4,
pointHoverRadius: 4
},
{
data: data2.map((v, i) => imageIndexes.includes(i) ? v + 1.2 : null),
fill: false,
pointStyle: icon,
pointRadius: 22,
pointHoverRadius: 22
}
]
},
options: {
responsive: false,
title: {
display: false
},
legend: {
display: false
},
tooltips: {
filter: tooltipItem => tooltipItem.datasetIndex == 2,
titleFontSize: 16,
titleAlign: 'center',
callbacks: {
title: (tooltipItem) => tooltipItem.length == 0 ? null : tooltipText,
label: () => null
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 6,
stepSize: 1
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" style="width: 500px; height: 200px"></canvas>

How to change style of the selected point in Google Charts?

I'm using Google Charts to build a Line Graph and I need to change the style of the selected point.
The code below customizes the points individually when the graph loads, but I need to style the point after the user selects/clicks the point. I need to change the color, size and stroke-width of the selected point.
function drawChart() {
var data = google.visualization.arrayToDataTable
([['X', 'Y', {'type': 'string', 'role': 'style'}],
[1, 3, null],
[2, 2.5, null],
[3, 3, null],
[4, 4, null],
[5, 4, null],
[6, 3, 'point { size: 18; shape-type: star; fill-color: #a52714; visible: false }'],
[7, 2.5, null],
[8, 3, null]
]);
var options = {
legend: 'none',
hAxis: { minValue: 0, maxValue: 9 },
curveType: 'function',
pointSize: 7,
dataOpacity: 0.3
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
https://jsfiddle.net/api/post/library/pure/

How to make a custom tooltip for each series in Google Line Chart

I am currently testing google charts and having difficulty in specifying my own custom tooltips.
my data is declared as below
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
data.addColumn('number', 'Cats');
data.addColumn({type: 'string', role: 'tooltip', p: {'html':true}});
data.addRows([0, 0, 0, 'hello'], [1, 10, 5, 'hello'],
[2, 23, 15, 'hello'],[3, 17, 9, 'hello'], [4, 18, 10, 'hello'],
[5, 9, 5, 'hello'],
see this jsFiddle http://jsfiddle.net/SecretSquirrel/rbwyhx1q/
It appears the custom tooltip is only affecting the first data column?
I thought it was pretty limited to only allow 1 tooltip per row, but if this is only 1 tooltip for the first column this is really quite useless.
Well you have to add another tooltip column for your second graft.
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
data.addColumn({type: 'string', role: 'tooltip', p: {'html':true}});
data.addColumn('number', 'Cats');
data.addColumn({type: 'string', role: 'tooltip', p: {'html':true}});
data.addRows([
[0, 0,'custom', 0, 'hello'], [1, 10,'custom', 5, 'hello'], [2, 23,'custom', 15, 'hello'],
[3, 17,'custom', 9, 'hello'], [4, 18,'custom', 10, 'hello'], [5, 9,'custom', 5, 'hello'],
[6, 11,'custom', 3, 'hello'], [7, 27,'custom', 19, 'hello'], [8, 33,'custom', 25, 'hello'],
[9, 40,'custom', 32, 'hello'], [10, 32,'custom', 24, 'hello'], [11, 35,'custom', 27, 'hello'],
[12, 30,'custom', 22, 'hello'], [13, 40,'custom', 32, 'hello'], [14, 42,'custom', 34, 'hello'],
[15, 47,'custom', 39,'hello'], [16, 44,'custom', 36,'hello'], [17, 48,'custom', 40, 'hello'],
[18, 52,'custom', 44,'hello'], [19, 54,'custom', 46,'hello'], [20, 42,'custom', 34, 'hello'],
[21, 55,'custom', 47,'hello'], [22, 56,'custom', 48,'hello'], [23, 57,'custom', 49,'hello']
]);
var options = {
width: 1000,
height: 563,
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
series: {
1: {curveType: 'function'}
}
};
var chart = new google.visualization.LineChart(document.getElementById('ex2'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="ex2"></div>

Google Line chart, remove extra lines

I am new in Google Graphs and I am attemting to generate this graph in the photo ( expected ) below
but I am getting a little bit different graph. I have three different letters and each letter contains their own values (A1, A2, A3, B1, B2 ... e.g.).
There the code which I am trying:
function drawChart () {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('string', 'Type');
data.addColumn('number', 'Value');
data.addRows([
[new Date(2014, 0, 30), 'A', 75],
[new Date(2014, 0, 30), 'A', 100],
[new Date(2014, 0, 30), 'A', 125],
[new Date(2014, 0, 31), 'A', 75],
[new Date(2014, 0, 31), 'A', 100],
[new Date(2014, 0, 31), 'A', 125],
[new Date(2014, 0, 30), 'B', 150],
[new Date(2014, 0, 30), 'B', 175],
[new Date(2014, 0, 30), 'B', 200],
[new Date(2014, 0, 31), 'B', 150],
[new Date(2014, 0, 31), 'B', 175],
[new Date(2014, 0, 31), 'B', 200],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: 'A',
calc: function (dt, row) {
return (dt.getValue(row, 1) == 'A') ? dt.getValue(row, 2) : null;
}
}, {
type: 'number',
label: 'B',
calc: function (dt, row) {
return (dt.getValue(row, 1) == 'B') ? dt.getValue(row, 2) : null;
}
}, {
type: 'number',
label: 'C',
calc: function (dt, row) {
return (dt.getValue(row, 1) == 'C') ? dt.getValue(row, 2) : null;
}
}, 2]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(view, {
height: 400,
width: 600,
hAxis: {
format: 'dd.MM.yyyy',
minValue: new Date(2014, 0, 29, 12),
maxValue: new Date(2014, 0, 31, 10)
},
series: {
0: {
// series A options
pointSize: 5,
lineWidth: 0
},
3: {
// this series draws the line
pointSize: 0,
lineWidth: 1,
visibleInLegend: false,
enableInteractivity: false,
color:'blue'
}
}
});
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
And it showing me this and I don't know how remove a line in 31.01.2014 -> A3 with 30.01.2014->B1 and color of line for blue dots blue color and for red dots red line is it possible? :
But expected one is below :
This is a case where my answer to your previous question is not the best approach to take for this, but there is an easy solution to modify your existing code to make this work. Remove the 2 from the end of the array passed to view.setColumns:
view.setColumns([0, {
type: 'number',
label: 'A',
calc: function (dt, row) {
return (dt.getValue(row, 1) == 'A') ? dt.getValue(row, 2) : null;
}
}, {
type: 'number',
label: 'B',
calc: function (dt, row) {
return (dt.getValue(row, 1) == 'B') ? dt.getValue(row, 2) : null;
}
}, {
type: 'number',
label: 'C',
calc: function (dt, row) {
return (dt.getValue(row, 1) == 'C') ? dt.getValue(row, 2) : null;
}
}]);
and adjust your series options:
series: {
0: {
// series A options
pointSize: 5,
lineWidth: 1
},
1: {
// series B options
pointSize: 5,
lineWidth: 1
},
2: {
// series C options
pointSize: 5,
lineWidth: 1
}
}

Google charts y-axis color

I'm using google charts api (line chart) and I want to change y-axis color from black to grey.
(the same color as the grid lines)
my code:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
var baseLineColor = '#a3d06e';
var lineColor = '#717171';
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('number', 'date');
dataTable.addColumn('number', 'sale');
dataTable.addRows([
[1, 2],
[2, 3],
[3, 3],
[4, 4],
[5, 5]
]);
var options = {
enableInteractivity: false,
tooltip: {trigger: 'none'},
pointSize: 0,
legend: 'none',
chartArea:{width:'94%',height:'70%'},
backgroundColor: '#6AB5D1',
series: { 0: { color: lineColor, pointSize: 5, lineWidth: 4 }},
hAxis: { textPosition: 'none', gridlines: {color:"#CCCCCC"} },
vAxis: { textPosition: 'none', baseline: 3, baselineColor: baseLineColor, gridlines: {color:"#CCCCCC"}}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataTable, options);
How can I do that?
Set the hAxis.baselineColor option:
hAxis: {
textPosition: 'none',
gridlines: {
color: "#CCCCCC"
},
baselineColor: '#CCCCCC'
}
you can change your x and y axis color in google api by setting the baselineColor and gridlineColor using these parameter.
vAxis:{
baselineColor: '#ccc',
gridlineColor: '#ccc',
}
Just a note: Remember that the baseline is the line that intersects the axis you are working with. So if you want to style the y-axis, you need to change the baselineColor of the h-axis.
I totally miss it at first.