Better labelling in google BarChart - javascript

I want to have custom labels in my BarChart, but using tics forces lines to be added and I want labels to be between lines to represent the area between two lines.
options = {
title: "- - - - - - - - Low - - - - - - - - - - - - - - - - Middle - - - - - - - - - - - - - - - - - - - - - - High - - - - - ",
animation: {
startup: 'true',
easing: 'linear',
duration: 500
},
height: 100,
legend: {
position: 'none'
},
hAxis: {
maxValue: 10,
minValue: 0,
ticks: [{
v: 0,
f: ''
}, {
v: 3,
f: ''
}, {
v: 7,
f: ''
}, {
v: 10,
f: ''
}]
},
width: 700,
tooltip: {
trigger: 'hover'
},
backgroundColor: "transparent",
};
I have made a fiddle showing the functions I'm looking for. I would be super happy if someone knows how to solve this correctly:
https://jsfiddle.net/zkcps3h8/2/
Functions the fiddle represents:
Having three sections of: Low, medium, high
Having lines dividing these sections
Having labels under or above these colums
Any way to solve this problem is appreciated.

there are no standard config options you can use to get the desired layout,
but you can add labels manually, when the chart finishes drawing.
use ticks to add lines for the desired sections,
then use those lines for reference when adding the labels,
see following working snippet...
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
var options = {
animation: {
startup: 'true',
easing: 'linear',
duration: 500
},
height: 100,
legend: {
position: 'none'
},
hAxis: {
maxValue: 10,
minValue: 0,
gridlines: {
color: '#757575'
},
ticks: [{
v: 0,
f: ''
}, {
v: 3,
f: ''
}, {
v: 7,
f: ''
}, {
v: 10,
f: ''
}]
},
tooltip: {
trigger: 'hover'
},
backgroundColor: 'transparent',
chartArea: {
backgroundColor: 'transparent',
height: '100%',
width: '100%',
top: 60,
left: 72,
right: 24,
bottom: 24
},
height: '100%',
width: '100%'
};
var container = document.getElementById('s-graph');
var data_array = $(container).data('values');
data_array.unshift(['Something', 'Fun', {role: 'style'}]);
var data = new google.visualization.arrayToDataTable(data_array);
var chart = new google.visualization.BarChart(container);
google.visualization.events.addListener(chart, 'animationfinish', function () {
var chartElements = container.getElementsByTagName('rect');
var chartArea = chartElements[0];
var sectionLabels = ['Low', 'Middle', 'High'];
var svg = container.getElementsByTagName('svg')[0];
var svgNS = svg.namespaceURI;
// clone existing label for style, font
var defaultLabel = container.getElementsByTagName('text')[0];
var labelIndex = -1;
var xCoordLeft = parseFloat(chartArea.getAttribute('x'));
Array.prototype.forEach.call(chartElements, function(rect) {
if (rect.getAttribute('fill') === options.hAxis.gridlines.color) {
if (labelIndex > -1) {
var xCoordRect = parseFloat(rect.getAttribute('x'));
var xCoordLabel = ((xCoordRect - xCoordLeft) / 2) + xCoordLeft;
// top label
var label = defaultLabel.cloneNode(true);
label.setAttribute('x', xCoordLabel);
label.setAttribute('y', chartArea.getAttribute('y'));
label.textContent = sectionLabels[labelIndex];
svg.appendChild(label);
// adjust for length of label
var labelBounds = label.getBBox();
xCoordLabel = xCoordLabel + (labelBounds.width / 2);
label.setAttribute('x', xCoordLabel);
// bottom label
label = label.cloneNode(true);
label.setAttribute('y', parseFloat(chartArea.getAttribute('height')) + parseFloat(chartArea.getAttribute('y')) + labelBounds.height);
svg.appendChild(label);
xCoordLeft = xCoordRect;
}
labelIndex++;
}
});
});
window.addEventListener('resize', function () {
chart.draw(data, options);
});
chart.draw(data, options);
});
<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 data-values="[["Tom", 7.2, "#ed341c"], ["Nisse", 6.4, "#16593a"]]" id="s-graph"></div>
note: changes made manually will not show when using chart method getImageURI,
if you need an image of the chart, you can use html2canvas

You should be able to do this via the ticks property under hAxis
Checkout this https://jsfiddle.net/5dqhxbqq/
And here is the documentation on it. hAxis.ticks

Related

Bubbles chart: how to avoid bubbles being cut off? google visualization

I'm using google visualization for bubble chart, data to x axis and Y axis is dynamic. I'm facing issue here is that bubbles get cut-off and there size is also not uniform.
using following options
options = {
'title': 'Chart',
'width': '100%',
'height': 550,
legend: {position: 'right'},
vAxis: {
title: 'Score',
viewWindow: {
min: 0,
max: 5
},
baselineColor: {
color: '#4c78c6',
},
sizeAxis : {minValue: 0, maxSize: 15},
ticks: [1, 2, 3, 4, 5]
},
hAxis: {
title: 'Years',
baselineColor: {
color: '#4c78c6',
}
},
sizeAxis : {minValue: 0, maxSize: 15},
bubble: {
textStyle: {
color: 'none',
}
},
tooltip: {
isHtml: true,
},
colors: colors,
chartArea: { width: "30%", height: "50%" }
};
EDIT data passed to
var rows = [
['ID','YEAR','SCORE', 'AVG1', 'AVG']
['Deka marc', 2.5, 5, '76-100%', 100]
['Max cala', 28.2,3.4,'76-100%', 77]
['shane root',4.2, 1, '0-25%', 0]
]
var data = google.visualization.arrayToDataTable(rows);
from above array I'm removing element 3 on hover as do not wish to show in tooltip. AVG1 column is for legend
getting o/p like this
use
var rangeX = data.getColumnRange(1);
to know the range of column
and then use
hAxis: {
viewWindow: {
min: rangeX.min-10,
max: rangeX.max+10
}
},
}
do similarly for yAxis
https://jsfiddle.net/geniusunil/nt4ymrLe/4/
Add inside hAxis the viewWindow option.
This is a sample code:
viewWindow: {
min: 0,
max: 40
}
You can change max according your biggest value in your dataset you want to show. I mean if is 30 (as in your example) you can set max: 40, or if is 75 you can set max equal to 85.
JSfiddle here.
to find the range of each axis dynamically, use data table method --> getColumnRange
then you can use the ticks option to increase the range.
var rangeX = data.getColumnRange(1);
var ticksX = [];
for (var i = (Math.floor(rangeX.min / 10) * 10); i <= (Math.ceil(rangeX.max / 10) * 10); i = i + 10) {
ticksX.push(i);
}
var rangeY = data.getColumnRange(2);
var ticksY = [];
for (var i = Math.floor(rangeY.min) - 1; i <= Math.ceil(rangeY.max) + 1; i++) {
ticksY.push(i);
}
to make the size of the bubble uniform, set minSize & maxSize to the same value.
sizeAxis : {minSize: 15, maxSize: 15},
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var rows = [
['ID','YEAR','SCORE', 'AVG1', 'AVG'],
['Deka marc', 2.5, 5, '76-100%', 100],
['Max cala', 28.2,3.4,'76-100%', 77],
['shane root',4.2, 1, '0-25%', 0]
];
var data = google.visualization.arrayToDataTable(rows);
var rangeX = data.getColumnRange(1);
var ticksX = [];
for (var i = (Math.floor(rangeX.min / 10) * 10); i <= (Math.ceil(rangeX.max / 10) * 10); i = i + 10) {
ticksX.push(i);
}
var rangeY = data.getColumnRange(2);
var ticksY = [];
for (var i = Math.floor(rangeY.min) - 1; i <= Math.ceil(rangeY.max) + 1; i++) {
ticksY.push(i);
}
var options = {
title: 'Chart',
width: '100%',
height: 550,
legend: {position: 'right'},
vAxis: {
title: 'Score',
baselineColor: {
color: '#4c78c6',
},
sizeAxis : {minSize: 15, maxSize: 15},
ticks: ticksY
},
hAxis: {
title: 'Years',
baselineColor: {
color: '#4c78c6',
},
ticks: ticksX
},
sizeAxis : {minSize: 10, maxSize: 10},
bubble: {
textStyle: {
color: 'none',
}
},
tooltip: {
isHtml: true,
},
//colors: colors,
chartArea: { width: "30%", height: "50%" }
};
var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Add 10% of the difference between the max and min
vAxis: {
viewWindow: {
min: rangeY.min - ((+rangeY.max - rangeY.min) * 10 / 100),
max: rangeY.max + ((+rangeY.max - rangeY.min) * 10 / 100)
}
},
hAxis: {
viewWindow: {
min: rangeX.min - ((+rangeX.max - rangeX.min) * 10 / 100),
max: rangeX.max + ((+rangeX.max - rangeX.min) * 10 / 100)
}
},

Multiple group on AxisX with javascript

I'm trying to create a chart with multiple AxisX with a javascript library (google or chartjs preferable).
I have made an example on excel to illustrate what i'm looking for, here is the example:
I've tried the next fiddle but obviously without success.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Month', ['Activo, inactivo'], ['Activo, inactivo'], ['Activo, inactivo'], ['Activo, inactivo']],
['Gestor A', [165,100], [938,800], [522,100], [998, 1000]],
['Gestor B', [135,90], [1120,1000], [599,1000], [1268,700]],
['Gestor C', [157,70], [1167,800], [587,400], [807,900]],
['Gestor D', [139,160], [1110,1200], [615,500], [968,1000]],
['Gestor E', [136,200], [691,800], [629,700], [1026,1200]]
]);
var options = {
title : 'Monthly Coffee Production by Country',
vAxis: {title: 'Cups'},
hAxis: {title: ['Month']},
seriesType: 'bars',
series: {5: {type: 'line'}}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
google charts does not offer multiple group labels
but you can add them manually on the chart's 'ready' event
see following working snippet,
the position of the x-axis labels are used to draw the group labels and lines
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Month', 'Gestor A', 'Gestor B', 'Gestor C', 'Gestor D', 'Gestor E'],
['Activo', 165, 135, 157, 139, 136],
['Inactivo', 100, 90, 70, 160, 200],
['Activo', 938, 1120, 1167, 1110, 691],
['Inactivo', 800, 1000, 800, 1200, 800],
['Activo', 522, 599, 587, 615, 629],
['Inactivo', 100, 1000, 400, 500, 700],
['Activo', 998, 1268, 807, 968, 1026],
['Inactivo', 1000, 700, 900, 1000, 1200]
]);
var options = {
chartArea: {
bottom: 64,
left: 48,
right: 16,
top: 64,
width: '100%',
height: '100%'
},
hAxis: {
maxAlternation: 1,
slantedText: false
},
height: '100%',
legend: {
alignment: 'end',
position: 'top'
},
seriesType: 'bars',
title : 'Title',
width: '100%'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ComboChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var chartLayout = chart.getChartLayoutInterface();
var chartBounds = chartLayout.getChartAreaBoundingBox();
var indexGroup = 0;
var indexRow = 0;
var months = ['Janeiro', 'Fevereiro', 'Marco', 'Abril'];
var xCoords = [];
Array.prototype.forEach.call(container.getElementsByTagName('text'), function(text) {
// process x-axis labels
var xAxisLabel = data.getFilteredRows([{column: 0, value: text.textContent}]);
if (xAxisLabel.length > 0) {
// save label x-coordinate
xCoords.push(parseFloat(text.getAttribute('x')));
// add first / last group line
if (indexRow === 0) {
addGroupLine(chartBounds.left, chartBounds.top + chartBounds.height);
}
if (indexRow === (data.getNumberOfRows() - 1)) {
addGroupLine(chartBounds.left + chartBounds.width, chartBounds.top + chartBounds.height);
}
// add group label / line
if ((indexRow % 2) !== 0) {
// calc label coordinates
var xCoord = xCoords[0] + ((xCoords[1] - xCoords[0]) / 2);
var yCoord = parseFloat(text.getAttribute('y')) + (parseFloat(text.getAttribute('font-size')) * 1.5);
// add group label
var groupLabel = text.cloneNode(true);
groupLabel.setAttribute('y', yCoord);
groupLabel.setAttribute('x', xCoord);
groupLabel.textContent = months[indexGroup];
text.parentNode.appendChild(groupLabel);
// add group line
addGroupLine(chartBounds.left + ((chartBounds.width / 4) * (indexGroup + 1)), chartBounds.top + chartBounds.height);
indexGroup++;
xCoords = [];
}
indexRow++;
}
});
function addGroupLine(xCoord, yCoord) {
var parent = container.getElementsByTagName('g')[0];
var groupLine = container.getElementsByTagName('rect')[0].cloneNode(true);
groupLine.setAttribute('x', xCoord);
groupLine.setAttribute('y', yCoord);
groupLine.setAttribute('width', 0.8);
groupLine.setAttribute('height', options.chartArea.bottom);
parent.appendChild(groupLine);
}
});
window.addEventListener('resize', function () {
chart.draw(data, options);
});
chart.draw(data, options);
});
html, body {
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
}
.chart {
height: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="chart" id="chart_div"></div>
note: elements drawn manually will not show when using chart method getImageURI,
if you need an image of the chart, you can use html2canvas
Exemple with chartjs - https://jsfiddle.net/6c0L1yva/392/
JAVASCRIPT -
var ctx = document.getElementById('c');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Active;January", "Inactive;January", "Active;February", "Inactive;February", "Active;March", "Inactive;March"],
datasets: [{
label: "Gestor A",
backgroundColor: "blue",
data: [3, 7, 4, 2, 3, 1]
}, {
label: "Gestor B",
backgroundColor: "red",
data: [4, 3, 5, 3, 1, 2]
}, {
label: "Gestor C",
backgroundColor: "green",
data: [7, 2, 6, 8, 2, 1]
}]
},
options:{
scales:{
xAxes:[
{
id:'xAxis1',
type:"category",
ticks:{
callback:function(label){
var state = label.split(";")[0];
var user = label.split(";")[1];
return state;
}
}
},
{
id:'xAxis2',
type:"category",
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
ticks:{
callback:function(label){
var state = label.split(";")[0];
var user = label.split(";")[1];
if(state === "Inactive"){
return user;
}else{
return "";
}
}
}
}],
yAxes:[{
ticks:{
beginAtZero:true
}
}]
}
}
});

Google chart stacked bar chart two positive scale

I'm currently working on a chart using google chart api, but i struggle at making a twice positive horizontal scale.
Like : 50 25 0 25 50 with a stacked chart bar centered on the '0' in the scale.
I kind of got it centered using a "dummy" invisible bar to push everything, but i can't find a way to get the horizontal axis label customized without editing the windowsview.
here's my actual code :
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawAnnotations);
function findMax(arr) {
var max = 0;
for (var n in arr) {
if (n > 0) {
var cMax = arr[n][2];
if (cMax > max)
max = cMax
}
}
return (max);
}
function findLine(arr) {
var max = 0;
for (var n in arr) {
if (n > 0) {
var cMax = arr[n][2] + arr[n][3] + arr[n][4];
if (cMax > max)
max = cMax
}
}
return (max / 2);
}
function space(arr, maxL) {
var max = findMax(arr);
for (var n in arr) {
if (n > 0) {
arr[n][1] = max - arr[n][2] + (maxL);
}
}
}
function drawAnnotations() {
var raw_data = [];
raw_data.push( ['Compétence', 'invisible', 'Expert', 'Certifié', 'Non certifié'] );
raw_data.push( ['Java', 0, 24, 31, 12] );
raw_data.push( ['PHP', 0, 17, 22, 10] );
raw_data.push( ['JavaScript', 0, 6, 10, 22] );
raw_data.push( ['Cpp', 0, 0, 0, 50] );
raw_data.push( ['C#', 0, 5, 10, 15] );
var maxL = findLine(raw_data);
space(raw_data, maxL);
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
enableInteractivity: false,
width: 600, height: 400,
legend : 'none',
bar: { groupWidth: '85%' },
colors: ['ffffff','gray', 'yellow', 'red'],
hAxis: {
title: '',
baselineColor: '#fff',
gridlineColor: '#fff'
},
vAxis: {
title: '',
baselineColor: '#fff',
gridlineColor: '#fff'
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSfiddle Link
Currently i got what i want exept for the horizontal scale which is not set as i wish it to be.
(I tried to use multiple axes but it has proven to be unseccessfull).
edit: I add a link to an image of what kind of chart (scale) i'm looking to do.
UPDATE
I kinda got it working now :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var raw_data = [];
raw_data.push( ['Compétence', 'Expert', 'Certifié', 'Non certifié'] );
raw_data.push( ['Java', -24, 45, 12] );
raw_data.push( ['PHP', -17, 22, 10] );
raw_data.push( ['JavaScript', -6, 10, 22] );
raw_data.push( ['Cpp', -0, 0, 50] );
raw_data.push( ['C#', -5, 10, 15] );
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
width: $(window).width() * 0.8, height: 400,
legend : 'none',
bar: { groupWidth: '85%' },
colors: ['gray', 'yellow', 'red'],
interpolateNulls: true,
hAxis: {
title: 'Number',
gridlines: {
color: 'transparent'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(window).load(function() {
$('text').each(function(i, el) {
if ($(this).text()[0] == '-')
$(this).text($(this).text().substr(1));
});
});
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I had to change the google lib i was using :
previously was :
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
and now i'm using :
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
I'm not sure why it change something but without this change $(window).load was unable to reach "text" and i wasn't able to edit it.
Now i'm just converting a part of my chart to negative (the one i wanted on the left) and change the "negative" values from the scale using jquery.
There's just one thing left , the tooltip still show the negative value when you point on the "gray" area of the chart.
I still hope it may help someone else who struggle with this particular problem.
In fact, instead of modifying axis text via jQuery you could customize it via ticks feature as shown below:
hAxis: {
ticks: [{ v: -25, f: '25' }, 0, 25, 50, 75]
}
Regrading customizing tooltip label, you could consider the following solution to display non-negative value:
1) Attach onmouseover event to Google Chart:
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
setTooltipContent(data, e);
});
2) Override tooltip negative value:
function setTooltipContent(data, e) {
if (e.row != null && e.column == 1) {
var val = Math.abs(data.getValue(e.row, 1));
var tooltipTextLabel = $(".google-visualization-tooltip-item-list li:eq(1) span:eq(1)");
tooltipTextLabel.text(val.toString());
}
}
Complete example
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var raw_data = [];
raw_data.push(['Compétence', 'Expert', 'Certifié', 'Non certifié']);
raw_data.push(['Java', -24, 45, 12]);
raw_data.push(['PHP', -17, 22, 10]);
raw_data.push(['JavaScript', -6, 10, 22]);
raw_data.push(['Cpp', -0, 0, 50]);
raw_data.push(['C#', -5, 10, 15]);
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
width: $(window).width() * 0.8, height: 400,
legend: 'none',
bar: { groupWidth: '85%' },
colors: ['gray', 'yellow', 'red'],
interpolateNulls: true,
tooltip: {isHtml: true},
hAxis: {
title: 'Number',
gridlines: {
color: 'transparent'
},
ticks: [{ v: -25, f: '25' }, 0, 25, 50, 75]
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
setTooltipContent(data, e);
});
}
function setTooltipContent(data, e) {
if (e.row != null && e.column == 1) {
var val = Math.abs(data.getValue(e.row, 1));
var tooltipTextLabel = $(".google-visualization-tooltip-item-list li:eq(1) span:eq(1)");
tooltipTextLabel.text(val.toString());
}
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
JSFiddle

Draw a Line Chart with both solid and dotted line in it with angular nvd3js directive?

I'm using angular-nvd3 directive for making a custom line chart display counting number of guest in specific period time range as follow :
current Time - 2 --> current Time : will be display as straight line
current Time --> current Time + 2 : will be display as dotted line .
Here is my implementation code with only straight line:
var app = angular.module('plunker', ['nvd3']);
app.controller('MainCtrl', function($scope) {
$scope.options = {
chart: {
type: 'lineChart',
tooltips: false,
height: 450,
margin : {
top: 20,
right: 20,
bottom: 40,
left: 55
},
x: function(d){ return d.x; },
y: function(d){ return d.y; },
useInteractiveGuideline: false,
dispatch: {
stateChange: function(e){ console.log("stateChange"); },
changeState: function(e){ console.log("changeState"); },
tooltipShow: function(e){ console.log("tooltipShow"); },
tooltipHide: function(e){ console.log("tooltipHide"); }
},
xAxis: {
axisLabel: 'Time (ms)'
},
yAxis: {
axisLabel: 'Voltage (v)',
tickFormat: function(d){
return d3.format('.02f')(d);
},
axisLabelDistance: 30
},
callback: function(chart){
console.log("!!! lineChart callback !!!");
}
},
title: {
enable: true,
text: 'Title for Line Chart'
}
};
$scope.data = sinAndCos();
/*Random Data Generator */
function sinAndCos() {
var sin = [],sin2 = [],
cos = [];
//Data is represented as an array of {x,y} pairs.
for (var i = 0; i < 100; i++) {
sin.push({x: i, y: Math.sin(i/10)});
sin2.push({x: i, y: i % 10 == 5 ? null : Math.sin(i/10) *0.25 + 0.5});
cos.push({x: i, y: .5 * Math.cos(i/10+ 2) + Math.random() / 10});
}
//Line chart data should be sent as an array of series objects.
return [
{
values: [{x:7,y:100},{x:8,y:40},{x:9,y:70}],
key: 'Sine Wave', //key - the name of the series.
color: '#ff7f0e', //color - optional: choose your own line color.
strokeWidth: 2
},
{
values: [{x:7,y:200},{x:8,y:140},{x:9,y:170},{x:10,y:120},{x:11,y:180}],
key: 'Cosine Wave',
color: '#2ca02c'
},
{
values: [{x:7,y:300},{x:8,y:240},{x:9,y:270},{x:10,y:220},{x:11,y:280}],
key: 'Another sine wave',
color: '#7777ff'
}
];
};
});
Here is the plunker for this : http://plnkr.co/edit/lBKFld?p=preview
Anyone can provide some help that would get my great appreciate.
Thanks
{
values: [{x:7,y:200},{x:8,y:140},{x:9,y:170},{x:10,y:120},{x:11,y:180}],
key: 'Cosine Wave',
color: '#2ca02c',
classed: 'dashed' // <-- Now use CSS to make the line dashed
}
STYLE!!!
.dashed {
stroke-dasharray: 5,5;
}

How can I change the width of the bars in a highchart?

With a bar chart like this one, is is possible to change the width of the bars to represent another data attribute, say the weight of the fruits. The heavier the fruit is, the thicker the bar.
You play with the script here. I am open to other javascript plotting libraries that could do that as long as they are free.
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Column chart with negative values'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y +'';
}
},
credits: {
enabled: false
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
// I would like something like this (3.5, 6 etc is the width) :
// data: [[5, 3.4], [3, 6], [4, 3.4], [7, 2], [2, 5]]
}, {
name: 'Jane',
data: [2, -2, -3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, -2, 5]
}]
});
});
});​
pointWidth is what you require to set the width of the bars. try
plotOptions: {
series: {
pointWidth: 15
}
}
This display bars with the width of 15px. Play around here. Just made an edit to the already existing code.
I use a set of area charts to simulate a variable-width-column/bar-chart. Say, each column/bar is represented by a rectangle area.
See my fiddle demo (http://jsfiddle.net/calfzhou/TUt2U/).
$(function () {
var rawData = [
{ name: 'A', x: 5.2, y: 5.6 },
{ name: 'B', x: 3.9, y: 10.1 },
{ name: 'C', x: 11.5, y: 1.2 },
{ name: 'D', x: 2.4, y: 17.8 },
{ name: 'E', x: 8.1, y: 8.4 }
];
function makeSeries(listOfData) {
var sumX = 0.0;
for (var i = 0; i < listOfData.length; i++) {
sumX += listOfData[i].x;
}
var gap = sumX / rawData.length * 0.2;
var allSeries = []
var x = 0.0;
for (var i = 0; i < listOfData.length; i++) {
var data = listOfData[i];
allSeries[i] = {
name: data.name,
data: [
[x, 0], [x, data.y],
{
x: x + data.x / 2.0,
y: data.y,
dataLabels: { enabled: true, format: data.x + ' x {y}' }
},
[x + data.x, data.y], [x + data.x, 0]
],
w: data.x,
h: data.y
};
x += data.x + gap;
}
return allSeries;
}
$('#container').highcharts({
chart: { type: 'area' },
xAxis: {
tickLength: 0,
labels: { enabled: false}
},
yAxis: {
title: { enabled: false}
},
plotOptions: {
area: {
marker: {
enabled: false,
states: {
hover: { enabled: false }
}
}
}
},
tooltip: {
followPointer: true,
useHTML: true,
headerFormat: '<span style="color: {series.color}">{series.name}</span>: ',
pointFormat: '<span>{series.options.w} x {series.options.h}</span>'
},
series: makeSeries(rawData)
});
});
Fusioncharts probably is the best option if you have a license for it to do the more optimal Marimekko charts…
I've done a little work trying to get a Marimekko charts solution in highcharts. It's not perfect, but approximates the first Marimekko charts example found here on the Fusion Charts page…
http://www.fusioncharts.com/resources/chart-tutorials/understanding-the-marimekko-chart/
The key is to use a dateTime axis, as that mode provides you more flexibility for the how you distribute points and line on the X axis which provides you the ability to have variably sized "bars" that you can construct on this axis. I use 0-1000 second space and outside the chart figure out the mappings to this scale to approximate percentage values to pace your vertical lines. Here ( http://jsfiddle.net/miken/598d9/2/ ) is a jsfiddle example that creates a variable width column chart.
$(function () {
var chart;
Highcharts.setOptions({
colors: [ '#75FFFF', '#55CCDD', '#60DD60' ]
});
$(document).ready(function() {
var CATEGORY = { // number out of 1000
0: '',
475: 'Desktops',
763: 'Laptops',
1000: 'Tablets'
};
var BucketSize = {
0: 475,
475: 475,
763: 288,
1000: 237
};
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'area'
},
title: {
text: 'Contribution to Overall Sales by Brand & Category (in US$)<br>(2011-12)'
},
xAxis: {
min: 0,
max: 1000,
title: {
text: '<b>CATEGORY</b>'
},
tickInterval: 1,
minTickInterval: 1,
dateTimeLabelFormats: {
month: '%b'
},
labels: {
rotation: -60,
align: 'right',
formatter: function() {
if (CATEGORY[this.value] !== undefined) {
return '<b>' + CATEGORY[this.value] + ' (' +
this.value/10 + '%)</b>';
}
}
}
},
yAxis: {
max: 100,
gridLineWidth: 0,
title: {
text: '<b>% Share</b>'
},
labels: {
formatter: function() {
return this.value +'%'
}
}
},
tooltip: {
shared: true,
useHTML: true,
formatter: function () {
var result = 'CATEGORY: <b>' +
CATEGORY[this.x] + ' (' + Highcharts.numberFormat(BucketSize[this.x]/10,1) + '% sized bucket)</b><br>';
$.each(this.points, function(i, datum) {
if (datum.point.y !== 0) {
result += '<span style="color:' +
datum.series.color + '"><b>' +
datum.series.name + '</b></span>: ' +
'<b>$' + datum.point.y + 'K</b> (' +
Highcharts.numberFormat(
datum.point.percentage,2) +
'%)<br/>';
}
});
return (result);
}
},
plotOptions: {
area: {
stacking: 'percent',
lineColor: 'black',
lineWidth: 1,
marker: {
enabled: false
},
step: true
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 100,
borderWidth: 1,
title: {
text : 'Brand:'
}
},
series: [ {
name: 'HP',
data: [
[0,298],
[475,109],
[763,153],
[1000,153]
]
}, {
name: 'Dell',
data: [
[0,245],
[475,198],
[763,120],
[1000,120]
]
}, {
name: 'Sony',
data: [
[0,335],
[475,225],
[763,164],
[1000,164]
]
}]
},
function(chart){
// Render bottom line.
chart.renderer.path(['M', chart.plotLeft, chart.plotHeight + 66, 'L', chart.plotLeft+chart.plotWidth, chart.plotHeight + 66])
.attr({
'stroke-width': 3,
stroke: 'black',
zIndex:50
})
.add();
for (var category_idx in CATEGORY) {
chart.renderer.path(['M', (Math.round((category_idx / 1000) * chart.plotWidth)) + chart.plotLeft, 66, 'V', chart.plotTop + chart.plotHeight])
.attr({
'stroke-width': 1,
stroke: 'black',
zIndex:4
})
.add();
}
});
});
});
It adds an additional array to allow you to map category names to second tic values to give you a more "category" view that you might want. I've also added code at the bottom that adds vertical dividing lines between the different columns and the bottom line of the chart. It might need some tweaks for the size of your surrounding labels, etc. that I've hardcoded in pixels here as part of the math, but it should be doable.
Using a 'percent' type accent lets you have the y scale figure out the percentage totals from the raw data, whereas as noted you need to do your own math for the x axis. I'm relying more on a tooltip function to provide labels, etc than labels on the chart itself.
Another big improvement on this effort would be to find a way to make the tooltip hover area and labels to focus and be centered and encompass the bar itself instead of the right border of each bar that it is now. If someone wants to add that, feel free to here.
If I got it right you want every single bar to be of different width. I had same problem and struggled a lot to find a library offering this option. I came to the conclusion - there's none.
Anyways, I played with highcharts a little, got creative and came up with this:
You mentioned that you'd like your data to look something like this: data: [[5, 3.4], [3, 6], [4, 3.4]], with the first value being the height and the second being the width.
Let's do it using the highcharts' column graph.
Step 1:
To better differentiate the bars, input each bar as a new series. Since I generated my data dynamically, I had to assign new series dynamically:
const objects: any = [];
const extra = this.data.length - 1;
this.data.map((range) => {
const obj = {
type: 'column',
showInLegend: false,
data: [range[1]],
animation: true,
borderColor: 'black',
borderWidth: 1,
color: 'blue'
};
for (let i = 0; i < extra; i++) {
obj.data.push(null);
}
objects.push(obj);
});
this.chartOptions.series = objects;
That way your different series would look something like this:
series: [{
type: 'column',
data: [5, 3.4]
}, {
type: 'column',
data: [3, 6]
}, {
type: 'column',
data: [4, 3.4]
}]
Step 2:
Assign this as plot options for highcharts:
plotOptions: {
column: {
pointPadding: 0,
borderWidth: 0,
groupPadding: 0,
shadow: false
}
}
Step 3:
Now let's get creative - to have the same starting point for all bars, we need to move every single one to the graph's start:
setColumnsToZero() {
this.data.map((item, index) => {
document.querySelector('.highcharts-series-' + index).children[0].setAttribute('x', '0');
});
}
Step 4:
getDistribution() {
let total = 0;
// Array including all of the bar's data: [[5, 3.4], [3, 6], [4, 3.4]]
this.data.map(item => {
total = total + item[0];
});
// MARK: Get xAxis' total width
const totalWidth = document.querySelector('.highcharts-axis-line').getBoundingClientRect().width;
let pos = 0;
this.data.map((item, index) => {
const start = item[0];
const width = (start * totalWidth) / total;
document.querySelector('.highcharts-series-' + index).children[0].setAttribute('width', width.toString());
document.querySelector('.highcharts-series-' + index).children[0].setAttribute('x', pos.toString());
pos = pos + width;
this.getPointsPosition(index, totalWidth, total);
});
}
Step 4:
Let's get to the xAxis' points. In the first functions modify the already existing points, move the last point to the end of the axis and hide the others. In the second function we clone the last point, modify it to have either 6 or 3 total xAxis points and move each of them to the correct position
getPointsPosition(index, totalWidth, total) {
const col = document.querySelector('.highcharts-series-' + index).children[0];
const point = (document.querySelector('.highcharts-xaxis-labels').children[index] as HTMLElement);
const difference = col.getBoundingClientRect().right - point.getBoundingClientRect().right;
const half = point.getBoundingClientRect().width / 2;
if (index === this.data.length - 1) {
this.cloneNode(point, difference, totalWidth, total);
} else {
point.style.display = 'none';
}
point.style.transform = 'translateX(' + (+difference + +half) + 'px)';
point.innerHTML = total.toString();
}
cloneNode(ref: HTMLElement, difference, totalWidth, total) {
const width = document.documentElement.getBoundingClientRect().width;
const q = total / (width > 1000 && ? 6 : 3);
const w = totalWidth / (width > 1000 ? 6 : 3);
let val = total;
let valW = 0;
for (let i = 0; i < (width > 1000 ? 6 : 3); i++) {
val = val - q;
valW = valW + w;
const clone = (ref.cloneNode(true) as HTMLElement);
document.querySelector('.highcharts-xaxis-labels').appendChild(clone);
const half = clone.getBoundingClientRect().width / 2;
clone.style.transform = 'translateX(' + (-valW + difference + half) + 'px)';
const inner = Math.round(val * 100) / 100;
clone.innerHTML = inner.toString();
}
}
In the end we have a graph looking something like this (not the data from this given example, but for [[20, 0.005], [30, 0.013333333333333334], [20, 0.01], [30, 0.005555555555555555], [20, 0.006666666666666666]] with the first value being the width and the second being the height):
There might be some modifications to do to 100% fit your case. F.e. I had to adjust the xAxis' points a specific starting and end point - I spared this part.

Categories