Flotchart stacked bar total label - javascript

I am using Flotcharts to create a stacked bar chart to show breakdown of values. I have this working so that once I hover over the stack it will show a tool tip with the value for that stack in it (you can see this in the second column).
What I need is at the top of all the stacks that it shows a label of the total value.
Something like High Charts Stacked Column.
You can see my code below. I loop through the data (using Smarty) and set it there.
// set the data
var data = [
{
label: 'Tenant',
data: [
{foreach $metrics.rent_applied_by_month as $rent_applied}
[{$rent_applied#index}, {$rent_applied.tenant_value|number_format:2:'.':''}],
{/foreach}
],
color: '#008000'
},
{
label: 'Benefit',
data: [
{foreach $metrics.rent_applied_by_month as $rent_applied}
[{$rent_applied#index}, {$rent_applied.benefit_value|number_format:2:'.':''}],
{/foreach}
],
color: '#0000ff'
}
];
// set the xasis labels
var ticks = [
{foreach $metrics.rent_applied_by_month as $rent_applied}
[{$rent_applied#index}, '{$rent_applied.period}'],
{/foreach}
];
// chart options
var options = {
series: {
stack: 0,
bars: {
show: true,
align: "center",
barWidth: 0.6,
fill: .75,
}
},
xaxis: {
ticks: ticks,
tickLength: 1
},
grid: {
hoverable: true,
clickable: true,
borderWidth: {
top: 0,
right: 0,
bottom: 1,
left: 1
},
borderColor: {
top: "#e5e5e5",
right: "#e5e5e5",
bottom: "#a5b2c0",
left: "#a5b2c0"
}
},
legend: {
show: true,
noColumns: 2,
position: "nw",
margin: [10, 0],
labelBoxBorderColor: null
}
};
$.plot("#rent_applied", data, options);

You'll need to loop through each of the bars in each stack to get the total value of all bars in each stack. With that total value in hand, you can pass it into flot's plot.pointOffset() method to get the position of the top of the stacked bars.
The code below has a sample method to get all of the values of a stack of bars, then uses the plot.pointOffset() to append a div showing the value on top of the bar.
$(function() {
var data = [{
data: [ [0, 21.51], [1, 32.50], [2, 47.14], [3, 10] ],
stack: 0,
label: 'Bottom'
}, {
data: [ [0, 37.77], [1, 24.65], [2, 7.67], [4, 15]],
stack: 0,
label: 'Top'
}];
var options = {
series: {
bars: {
show: true,
barWidth: .5,
align: "center"
},
points: { show: false }
}
};
var plot = $.plot($('#graph'), data, options);
displayBarValues();
// display values on top of bars
function displayBarValues() {
var plotData = plot.getData();
var xValueToStackValueMapping = [];
// loop through each data series
for (var i = 0; i < plotData.length; i++) {
var series = plotData[i];
// loop through each data point in the series
for (var j = 0; j < series.data.length; j++) {
var value = series.data[j];
// if the x axis value is not in the mapping, add it.
if (!xValueExistsInMapping(xValueToStackValueMapping, value[0])) {
xValueToStackValueMapping.push([value[0], 0]);
}
// add the value of the bar to the x value mapping
addValueToMapping(xValueToStackValueMapping, value[0], value[1]);
}
}
// loop through each of our stacked values and place them on the bar chart
$.each(xValueToStackValueMapping, function(i, value) {
// find the offset of the top left of the bar
var leftoffset = plot.pointOffset({ x: value[0] - .5, y: value[1] });
// find the offset of the top right of the bar (our bar width is .5)
var rightoffset = plot.pointOffset({ x: value[0] + .5, y: value[1] });
$('<div class="data-point-value">' + value[1] + '</div>').css({
left: leftoffset.left,
top: leftoffset.top - 14,
width: rightoffset.left - leftoffset.left,
textAlign: 'center'
}).appendTo(plot.getPlaceholder());
});
}
function xValueExistsInMapping(mapping, value) {
for (var i = 0; i < mapping.length; i++) {
if (mapping[i][0] !== undefined && mapping[i][0] === value) {
return true;
}
}
return false;
}
function addValueToMapping(mapping, xValue, yValue) {
for (var i = 0; i < mapping.length; i++) {
if (mapping[i][0] === xValue) {
mapping[i][1] = mapping[i][1] + yValue;
}
}
}
});
#graph {
margin: 0 auto;
text-align: center;
width: 600px;
height: 400px;
}
.data-point-value {
position: absolute;
white-space: nowrap;
font-size: 11px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.js"></script>
<script src="https://rawgit.com/flot/flot/master/jquery.flot.stack.js"></script>
<div id="graph"></div>

Related

Chartjs-gauge create circumference until certain value from data

I am creating 5 sections of gauge using chartjs-gauge. I am using the following data.
[150,200,250,300,400]
From this data, I want to display the circumference until 300. But the angle should calculated by including the last section value too. I had custom the text showing in section by setting it to empty string if more than 300. For section colour, I set 4 colours["green", "yellow", "orange", "red"]. Now, last section showing as silver colour which is default background of gauge. I have add rgba(0,0,0,0) to colour array ["green", "yellow", "orange", "red","rgba(0,0,0,0)"] which will show transparent colour for last section. But, when hover on section, it is responsive showing border. I would like to know if have other way to show the circumference until certain value from our data ,but calculating section area in chart using all value from data.
var data = [150, 200, 250, 300, 400];
var config = {
type: "gauge",
data: {
labels: ['Success', 'Warning', 'Warning', 'Error'],
datasets: [{
data: data,
value: 300,
backgroundColor: ["green", "yellow", "orange", "red"],
borderWidth: 2
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Gauge chart with datalabels plugin"
},
layout: {
padding: {
bottom: 30
}
},
needle: {
// Needle circle radius as the percentage of the chart area width
radiusPercentage: 2,
// Needle width as the percentage of the chart area width
widthPercentage: 3.2,
// Needle length as the percentage of the interval between inner radius (0%) and outer radius (100%) of the arc
lengthPercentage: 80,
// The color of the needle
color: "rgba(0, 0, 0, 1)"
},
valueLabel: {
formatter: Math.round
},
plugins: {
datalabels: {
display: true,
formatter: function(value, context) {
//return '>'+value;
if (value <= 300) {
return value;
} else {
return '';
}
},
color: function(context) {
//return context.dataset.backgroundColor;
return 'black';
},
//color: 'rgba(255, 255, 255, 1.0)',
/*backgroundColor: "rgba(0, 0, 0, 1.0)",*/
borderWidth: 0,
borderRadius: 5,
font: {
weight: "bold"
}
}
}
}
};
window.onload = function() {
var ctx = document.getElementById("chart").getContext("2d");
window.myGauge = new Chart(ctx, config);
};
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="jQuery/jquery-3.4.1.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gauge Chart with datalabels plugin</title>
<script src="https://unpkg.com/chart.js#2.8.0/dist/Chart.bundle.js"></script>
<script src="https://unpkg.com/chartjs-gauge#0.3.0/dist/chartjs-gauge.js"></script>
<script src="https://unpkg.com/chartjs-plugin-datalabels#0.7.0/dist/chartjs-plugin-datalabels.js"></script>
</head>
<body>
<div id="canvas-holder" style="width:100%">
<canvas id="chart"></canvas>
</div>
</body>
</html>
var data = [150, 200, 250, 300, 400];
colour_array = ["#11d8ee", "#3cc457", "#f12b0e", "#dda522", "#808080"];
let sum = data.reduce(function(a, b) {
return a + b;
}, 0);
var perc = 0;
perc_array = [];
for (i = 0; i < data.length; i++) {
perc = (data[i] / sum * 100).toFixed(2);
perc_array.push(perc);
}
Chart.plugins.register({ //increase distance between legend and chart
id: 'paddingBelowLegends',
beforeInit: function(chart, options) {
chart.legend.afterFit = function() {
this.height = this.height + 50; //custom 50 to value you wish
};
}
});
//when want to disable this plugin in other chart, paddingBelowLegends: false in plugin{}
var config = {
type: "doughnut",
data: {
labels: ['A', 'B', 'C', 'D', 'Others'],
datasets: [{
data: data,
value: data[(colour_array.length - 1)], //300
backgroundColor: colour_array,
borderWidth: 2
}]
},
options: {
responsive: true,
cutoutPercentage: 60,//thickness of chart
title: {
display: true,
text: "Gauge chart with datalabels plugin"
},
layout: {
padding: {
bottom: 30
}
},
valueLabel: {
formatter: Math.round,
display: false // hide the label in center of gauge
},
plugins: {
beforeInit: function(chart, options) {
chart.legend.afterFit = function() {
this.height = this.height + 50;
};
},
outlabels: {
display: true,
//text: '%l %v %p',//(label value percentage)the percentage automatically roundoff
//hide chart text label for last section-https://github.com/Neckster/chartjs-plugin-piechart-outlabels/issues/10#issuecomment-716606369
text: function(label) {
console.log(label);
highest_index = label['labels'].length - 1; //get highest index from the labels array
current_index = label['dataIndex']; //current index
value = label['dataset']['data'][label['dataIndex']]; //value of current index
const v = parseFloat(label['percent']) * 100;
if (current_index != highest_index) //to hide last section text label on chart.
{
//return value + ' , ' + `${v.toFixed(2)}%`;
return value+',\n'+`${v.toFixed(2)}%`;
} else {
return false;
}
},
color: 'white',
stretch: 12, //length of stretching
font: {
resizable: true,
minSize: 10,
maxSize: 14
},
padding: {
/*left:25,
right: 0
top:0,
bottom:0*/
}
},
//inner label:
datalabels: { //label on arc section
display: false,
formatter: function(value, context) {
if (value <= data[(colour_array.length - 2)]) //hide datalabel for last section
{
id = data.indexOf(value);
perc = perc_array[id];
return value + ' , ' + perc + '%';
} else {
return '';
}
},
color: function(context) {
return 'black';
},
borderWidth: 0,
borderRadius: 10,
font: {
weight: "bold",
},
anchor: "end" //'center' (default): element center, 'start': lowest element boundary, 'end': highest element boundary
}
},
legend: { //filter last section from legend chart labels
display: true,
//position: 'right',
labels: {
filter: function(legendItem, data) {
//ori-return legendItem !=1;
return !legendItem.text.includes('Others');
},
boxWidth: 20
}
},
rotation: 1 * Math.PI,
circumference: 1 * Math.PI,
tooltips: {
enabled: true,
mode: 'single',
filter: function(tooltipItem, data) { //disable display tooltip in last section
var label = data.labels[tooltipItem.index];
if (label == "Others") {
return false;
} else {
return true;
}
},
callbacks: { //custom tooltip text to show percentage amount (by default,showing real amount)
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
hovered_index = tooltipItem.index;
data_length = data.datasets[0].data.length;
var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
var currentValue = dataset.data[tooltipItem.index];
var percentage = (currentValue / total * 100).toFixed(2);
return currentValue + ' , ' + percentage + "%";
}
}
}
}
};
window.onload = function() {
var ctx = document.getElementById("chartJSContainer").getContext("2d");
window.myGauge = new Chart(ctx, config);
};
<html>
<head>
<script src="https://unpkg.com/chart.js#2.8.0/dist/Chart.bundle.js"></script>
<script src="https://unpkg.com/chartjs-gauge#0.3.0/dist/chartjs-gauge.js"></script>
<script src="https://unpkg.com/chartjs-plugin-datalabels#0.7.0/dist/chartjs-plugin-datalabels.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-piechart-outlabels"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="canvas-holder" style="width:50% align:center">
<canvas id="chartJSContainer"></canvas>
</div>
</body>
</html>

Better labelling in google BarChart

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

How to contain category data in tooltip

I've seen tutorials and posts about getting data from the x axis into the tooltip but I am overriding it with categories and cannot figure out how to get the x axis to show up in the tooltip.
This is what im working with:
function showTooltip(x, y, contents) {
$('<div id="tooltip" class="flot-tooltip tooltip"><div class="tooltip-arrow"></div>' + contents + '</div>').css({
top: y - 43,
left: x - 15,
}).appendTo("body").fadeIn(200);
}
var data = [[1492854610, -1240],[1492939020, -1273],[1493025073, -1279],[1493117066, -1186],[1493198484, -1269],[1493289175, -1198],[1493370646, -1280],[1493458518, -1255],[1493543731, -1275],[1493630250, -1273],[1493716306, -1279],[1493803609, -1264],[1493889258, -1276],[1493975557, -1278],[1494064529, -1235],[1494155440, -1160],[1494237980, -1224],[1494321047, -1280],[1494407990, -1271],[1494494125, -1275],[1494581609, -1257],[1494668321, -1252],[1494753220, -1277],[1494847855, -1140],[1494925963, -1278],[1495012537, -1275],[1495099289, -1269],[1495188205, -1227],[1495273568, -1244],[1495358329, -1272]];
$.plot($("#placeholder"), [{
label: "Delay: ",
data: data,
color: "#3a8ce5"
}], {
xaxis: {
mode: "categories",
tickLength: 0,
ticks: [[0, "1:50 AM"],[1, "1:17 AM"],[2, "1:11 AM"],[3, "2:44 AM"],[4, "1:21 AM"],[5, "2:32 AM"],[6, "1:10 AM"],[7, "1:35 AM"],[8, "1:15 AM"],[9, "1:17 AM"],[10, "1:11 AM"],[11, "1:26 AM"],[12, "1:14 AM"],[13, "1:12 AM"],[14, "1:55 AM"],[15, "3:10 AM"],[16, "2:06 AM"],[17, "1:10 AM"],[18, "1:19 AM"],[19, "1:15 AM"],[20, "1:33 AM"],[21, "1:38 AM"],[22, "1:13 AM"],[23, "3:30 AM"],[24, "1:12 AM"],[25, "1:15 AM"],[26, "1:21 AM"],[27, "2:03 AM"],[28, "1:46 AM"],[29, "1:18 AM"]]
},
yaxis: {
min: -2000,
max: 1000,
},
series: {
lines: {
show: true,
fill: true
},
points: {
show: true,
}
},
grid: {
hoverable: true,
clickable: true,
markings: [
{ color: '#000', lineWidth: 1, yaxis: { from: 0, to: 0 } },
]
},
legend: {
show: false
}
});
$("#placeholder").bind("plothover", function(event, pos, item) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var y = item.datapoint[1].toFixed();
showTooltip(item.pageX, item.pageY,
item.series.label + " = " + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
I am trying to get the times part of the categories. The item array has 3 pieces of data, none of which are the times
jFiddle:
http://jsfiddle.net/zw14y8c3/2/
The item.datapoint[0] data has the index of the x-axis tick. With that you can get the actual tick label from the ticks array:
var x = $("#placeholder").data('plot').getAxes().xaxis.ticks[item.datapoint[0]].label;
See the updated fiddle for the full example.

Flot Bar and Line chart [duplicate]

I've made this bar chart http://imageshack.com/a/img901/7186/cnOfhh.png, and the code for it is:
//compute & mark average color
for (var i = 0; i < zdata.length; i++) {
if (zdata[i].TargetTime == null) zdata[i].TargetTime = 0;
if (zdata[i].TimePlayed == null) zdata[i].TimePlayed = 0;
if (zdata[i].TargetTime >= zdata[i].TimePlayed) {
zdata[i]['Color'] = 'green';
} else {
zdata[i]['Color'] = 'red';
}
}
//localsitelist
var element = {
rt: 'D',
Id: rid,
courselist: clist,
selcourseId: selCid,
selcourse: selCname,
cartlist: wData,
selSiteId: lsid,
selsite: sitename,
dataList: zdata
}; //, carts: _mVM.availableCarts()}; //
//if rid exists, is update, else its new
var found = -1;
for (var k = 0; k < document.pvm.rapArray().length; k++) {
if (document.pvm.rapArray()[k].Id() == rid) {
document.pvm.rapArray()[k].update(element);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
//var data = [{ data: [[0, 1]], color: "red" }, { data: [[1, 2]], color: "yellow" },{ data: [[2, 3]], color: "green" }];
BarChart('#ChartD-Overview' + rid, values);
found = 1;
break;
}
}
if (found == -1) {
var rvm = new panelViewModel(element);
document.pvm.rapArray.push(rvm);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
BarChart('#ChartD-Overview' + rvm.Id(), values);
}
and the BarChart function:
function BarChart(id, data) {
$.plot(id, data, {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
stack: true,
xaxis: {
mode: "categories",
tickLength: 0
}
});
}
The problem is that I can't manage to get something like this https://imageshack.us/i/expGGpOkp, the little line should be zdata[i].TargetTime. I've tried something using stacked bar chart idea but the result was way different... What am I doing wrong? Can anyone help me with a suggestion to start with to get the same bar chart like in the last image?
Here is something like your second picture using another bar dataseries where the start and end of the bars are the same thereby reducing them to lines, you don't need to stack any of the bars just give them the right y-values (fiddle):
$(function () {
var dataBarsRed = {
data: [
[2, 3], ],
label: 'Bars in Red',
color: 'red'
};
var dataBarsGreen = {
data: [
[1, 2],
[3, 1],
[4, 3]
],
label: 'Bars in Green',
color: 'green'
};
var dataLines = {
data: [
[1, 3, 3],
[2, 3.5, 3.5],
[3, 1.5, 1.5],
[4, 2.5, 2.5]
],
label: 'Lines',
color: 'navy',
bars: {
barWidth: 0.5
}
};
var plot = $.plot("#placeholder", [dataBarsRed, dataBarsGreen, dataLines], {
points: {
show: false
},
lines: {
show: false
},
bars: {
show: true,
align: 'center',
barWidth: 0.6
},
grid: {
hoverable: true,
autoHighlight: true
},
xaxis: {
min: 0,
max: 5
},
yaxis: {
min: 0,
max: 5
}
});
});

Flot Bar Chart design

I've made this bar chart http://imageshack.com/a/img901/7186/cnOfhh.png, and the code for it is:
//compute & mark average color
for (var i = 0; i < zdata.length; i++) {
if (zdata[i].TargetTime == null) zdata[i].TargetTime = 0;
if (zdata[i].TimePlayed == null) zdata[i].TimePlayed = 0;
if (zdata[i].TargetTime >= zdata[i].TimePlayed) {
zdata[i]['Color'] = 'green';
} else {
zdata[i]['Color'] = 'red';
}
}
//localsitelist
var element = {
rt: 'D',
Id: rid,
courselist: clist,
selcourseId: selCid,
selcourse: selCname,
cartlist: wData,
selSiteId: lsid,
selsite: sitename,
dataList: zdata
}; //, carts: _mVM.availableCarts()}; //
//if rid exists, is update, else its new
var found = -1;
for (var k = 0; k < document.pvm.rapArray().length; k++) {
if (document.pvm.rapArray()[k].Id() == rid) {
document.pvm.rapArray()[k].update(element);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
//var data = [{ data: [[0, 1]], color: "red" }, { data: [[1, 2]], color: "yellow" },{ data: [[2, 3]], color: "green" }];
BarChart('#ChartD-Overview' + rid, values);
found = 1;
break;
}
}
if (found == -1) {
var rvm = new panelViewModel(element);
document.pvm.rapArray.push(rvm);
//build chart data
var values = []; //, series = Math.floor(Math.random() * 6) + 6;
for (var i = 0; i < zdata.length; i++) {
values[i] = {
data: [
[zdata[i].HoleSequence, zdata[i].TimePlayed]
],
color: zdata[i].Color
};
}
BarChart('#ChartD-Overview' + rvm.Id(), values);
}
and the BarChart function:
function BarChart(id, data) {
$.plot(id, data, {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
stack: true,
xaxis: {
mode: "categories",
tickLength: 0
}
});
}
The problem is that I can't manage to get something like this https://imageshack.us/i/expGGpOkp, the little line should be zdata[i].TargetTime. I've tried something using stacked bar chart idea but the result was way different... What am I doing wrong? Can anyone help me with a suggestion to start with to get the same bar chart like in the last image?
Here is something like your second picture using another bar dataseries where the start and end of the bars are the same thereby reducing them to lines, you don't need to stack any of the bars just give them the right y-values (fiddle):
$(function () {
var dataBarsRed = {
data: [
[2, 3], ],
label: 'Bars in Red',
color: 'red'
};
var dataBarsGreen = {
data: [
[1, 2],
[3, 1],
[4, 3]
],
label: 'Bars in Green',
color: 'green'
};
var dataLines = {
data: [
[1, 3, 3],
[2, 3.5, 3.5],
[3, 1.5, 1.5],
[4, 2.5, 2.5]
],
label: 'Lines',
color: 'navy',
bars: {
barWidth: 0.5
}
};
var plot = $.plot("#placeholder", [dataBarsRed, dataBarsGreen, dataLines], {
points: {
show: false
},
lines: {
show: false
},
bars: {
show: true,
align: 'center',
barWidth: 0.6
},
grid: {
hoverable: true,
autoHighlight: true
},
xaxis: {
min: 0,
max: 5
},
yaxis: {
min: 0,
max: 5
}
});
});

Categories