Draw straight line on google bar chart (combo) - javascript

I'm kinda bound to use google charts for one of my projects. What I need is, to display a bar chart, and in the bars a line intersecting each bar the represents another value. If you look at the jsfiddle below, you'll notice that the line chart only intersects the bars at the middle and continues to move forward towards other bars.
https://jsfiddle.net/ark7qbsc/
I would instead have, for example if you look at "Apples", for the line to intersect the entire bar (from start to finish) at y=2.5 and end within the bar, not to linger in the white spaces, nor make its way to the other bars.
Could anyone help me with this (Using only google charts.)
I've tired to inject null values after each data row, that at least removes the line from the white spaces. However, now there is just a dot on the centre of the bar. Looking a way to extend that to the entire bar width.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Fruit', 'Jane', 'Average'],
['Apples', 3, 2.5],
['Oranges', 2, 1.5],
['Pears', 4, 3],
['Bananas', 3, 2],
['Plums', 4, 3]
]);
// Set chart options
var options = {
title : 'Fruits distribution',
vAxis: {title: 'Fruits'},
hAxis: {title: 'Person'},
seriesType: 'bars',
series: {1:{type: 'line'}}
};
// Instantiate and draw the chart.
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Can't seem to get a line to be contained in the bar, from start to finish

not possible using standard methods / options,
but we can draw custom lines on the chart's ready event.
add nulls in between the rows to break the line.
['Fruit', 'Jane', 'Average'],
['Apples', 3, 2.5],
[null, null, null],
['Oranges', 2, 1.5],
[null, null, null],
we can use the following option to bring the bars closer together.
bar: {
groupWidth: '95%'
},
then we can use the circles to place the custom lines.
and we can use the chart's layout interface to find the width of the bars.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Fruit', 'Jane', 'Average'],
['Apples', 3, 2.5],
[null, null, null],
['Oranges', 2, 1.5],
[null, null, null],
['Pears', 4, 3],
[null, null, null],
['Bananas', 3, 2],
[null, null, null],
['Plums', 4, 3]
]);
var options = {
bar: {
groupWidth: '95%'
},
title : 'Fruits distribution',
vAxis: {title: 'Fruits'},
hAxis: {title: 'Person'},
seriesType: 'bars',
series: {1:{type: 'line'}}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ComboChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
// get chart layout and svg
var chartLayout = chart.getChartLayoutInterface();
var svg = document.querySelector('#chart_div svg');
var svgNS = svg.namespaceURI;
// process each circle
Array.prototype.forEach.call(container.getElementsByTagName('circle'), function(circle, index) {
// find width of the bar
var bounds = chartLayout.getBoundingBox('bar#0#' + (index * 2));
// create line
var line = document.createElementNS(svgNS, 'rect');
line.setAttribute('x', parseFloat(circle.getAttribute('cx')) - (bounds.width / 2));
line.setAttribute('y', parseFloat(circle.getAttribute('cy')));
line.setAttribute('width', bounds.width);
line.setAttribute('height', 1);
line.setAttribute('stroke', circle.getAttribute('fill'));
line.setAttribute('stroke-width', 2);
line.setAttribute('fill', circle.getAttribute('fill'));
circle.parentNode.appendChild(line);
});
});
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Plotly Hides Markers on Line Chart

I'm trying to create a line chart with markers for about 30 data points using Plotly. For some reason Plotly decides to hide the markers when the data points goes above a certain threshold such as 15. There is no reason to hide them as there is more than adequate space available. See below:
var trace1 = {
x: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
y: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
type: 'line',
marker: {
size: 10,
},
};
var data = [trace1];
Plotly.newPlot('myDiv', data);
https://codepen.io/ceds/pen/OJMOjjB
Any idea how to disable this?
I am not getting the exact problem why its not showing when more than 15 data points, But i have a solution using mode: 'lines+markers' property for marker and lines, as below,
var trace1 = {
x: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
y: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
type: 'line',
mode: 'lines+markers',
marker: {
size: 10,
},
};
var data = [trace1];
Plotly.newPlot('myDiv', data);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
Hope this help.

stacked column points connected with a dashed line highcharts

I tried many way and didnt get the result
may please help how can i generate this kind of chart in highchart.
That series will be available since Highcharts v8.0.0: https://github.com/highcharts/highcharts/issues/11311. For now you can use a combination of scatter and line series:
var scatterData = [2, 3, 7, 8, 9],
series = [{
type: 'scatter',
data: scatterData
}];
scatterData.forEach(function(el, i) {
series.push({
dashStyle: 'ShortDash',
data: [
[i, 5],
[i, el]
]
});
});
Highcharts.chart('container', {
series: series
});
Live demo: http://jsfiddle.net/BlackLabel/uwcL0h8b/
API Reference: https://api.highcharts.com/highcharts/series.line.dashStyle

Moving annotations on Bar Chart with Negative Values Google Chart

I am using google charts within an MVC project.
I am looking to implement a bar chart that has negative values.
I would like the annotations on the negative portion of the chart to be on the same side as the end of the bar (just like the positive, see image below, green box is where I would like annotations to be).
I cant seem to find any documentation on how this can be achieved.
Is it possible to move the annotation to the other side?
there are no standard config options that will move the annotations
but you can move them manually
however, the chart will actually move them back whenever activity occurs,
such as on bar hover
have to use a MutationObserver, or something, to keep them there
use chart methods --> getChartLayoutInterface().getXLocation(value)
to find the location
also, need to adjust the axis window to leave room for the labels
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
],
rows: [
{c:[{v: 'Omega'}, {v: -0.95}]},
{c:[{v: 'Large'}, {v: -0.92}]},
{c:[{v: 'Medium'}, {v: 2.76}]},
{c:[{v: 'Tiny'}, {v: 2.03}]}
]
});
var options = {
annotations: {
alwaysOutside: true,
stem: {
color: 'transparent'
},
textStyle: {
color: '#000000'
}
},
hAxis: {
// leave room for annotation
viewWindow: {
min: data.getColumnRange(1).min - 1
}
},
legend: {
position: 'none'
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var container = document.getElementById('chart');
var chart = new google.visualization.BarChart(container);
// move annotations
var observer = new MutationObserver(function () {
$.each($('text[text-anchor="start"]'), function (index, label) {
var labelValue = parseFloat($(label).text());
// only negative -- and -- not on tooltip
if ((labelValue < 0) && ($(label).attr('font-weight') !== 'bold')) {
var bounds = label.getBBox();
var chartLayout = chart.getChartLayoutInterface();
$(label).attr('x', chartLayout.getXLocation(labelValue) - bounds.width - 8);
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(view, options);
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Google Charts backgroundColor not working with example code

I use code from example page to create horizontal bars chart:
Option backgroundColor work for other chart types, like this and that.
Is there are way to change background color for Bars charts?
google.load('visualization', '1.1', {packages:['bar']});
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage'],
["King's pawn (e4)", 44],
["Queen's pawn (d4)", 31],
["Knight to King 3 (Nf3)", 12],
["Queen's bishop pawn (c4)", 10],
['Other', 3]
]);
var options = {
backgroundColor: { fill: '#000' },//this is not working
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" },
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
<script src="http://www.google.com/jsapi?fake=.js"></script>
<div id="top_x_div"></div>
chart
You're using a Material Bar chart (See the relevant documentation here.)
See the comment at the end of the documentation paragraph :
The Material Charts are in beta. The appearance and interactivity are
largely final, but the way options are declared is not. If you are
converting a Classic Bar Chart to a Material Bar Chart, you'll want to
replace this line:
chart.draw(data, options);
...with this:
chart.draw(data, google.charts.Bar.convertOptions(options));
So if you want your standard options taken into account you need to wrap them with google.charts.Bar.convertOptions().
Have a try, it works great. See a jsfiddle of it here.

google charts api - column chart - percentage above vertical bar along with normal values on left side of vaxis

I am using google charts to generate a column chart as shown in this image:
http://postimg.org/image/mt7tzwwob/
Here, data will be like [['a', 1], ['b', 2], ['c', 3]]
Here, I am getting values 1,2,3 on left left side of vaxis which is ok for me.
What I want extra is: The percentages at the top of the vertical bar.
x+2x+3x = 100, means, x=16, 2x=33, 3x=50. So, 16% should be at top of vertical bar with value 1.
How can I get these percentages ?
The ColumnChart's don't support adding labels like a percentage above the columns, but there is a work-around that involves using a ComboChart and a hidden line to add them in. Here's some example code that adds in labels (you can replace the labels with percents in you want):
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([
['Foo', 53, 'Foo text'],
['Bar', 71, 'Bar text'],
['Baz', 36, 'Baz text'],
['Cad', 42, 'Cad text'],
['Qud', 87, 'Qud text'],
['Pif', 64, 'Pif text']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 1, 2]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(view, {
height: 400,
width: 600,
series: {
0: {
type: 'bars'
},
1: {
type: 'line',
color: 'grey',
lineWidth: 0,
pointSize: 0,
visibleInLegend: false
}
},
vAxis: {
maxValue: 100
}
});
}
see it working here: http://jsfiddle.net/asgallant/QjQNX/
This only works well for charts that have a single series of data (as the labels will be misaligned if there is more than one series).

Categories

Resources