hide legend labels if zero data in jquery pie chart - javascript

I am trying to plot a pie chart with data set containing zero values.But pie chart shows only labels till data gets updated.
What if I wanted to show empty pie chart.
I have given:
var data = [
{
label: "Series1",
data: 0,
url: "http://stackoverflow.com"},
{
label: "Series2",
data: 0,
url: "http://serverfault.com"},
{
label: "Serie3",
data: 0,
url: "http://superuser.com"},
{
label: "Series4",
data: 0,
url: "http://www.google.com"},
{
label: "Series5",
data: 0,
url: "http://www.oprah.com"},
{
label: "Series6",
data: 0,
url: "http://www.realultimatepower.net/"}
];
var options = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
}
};
var plot = $.plot($("#graphLoaderDiv"), data, options);

Modify your label formatter function to return null if the series percent is zero.

After digging deeper I realized The best possible solution is to not to show pie chart if your data set values are zero.You either can do it editing following plugin or adding check inside your plotting function.
Download jquery.flot.pie.js from here
http://code.google.com/p/flot/issues/detail?id=530
Go to line No 411 and modify code as follows.
if( isNaN(angle) ) {
//var html = html = '<span class="pieLabel" id="pieLabelNoData" style="position:absolute;top:20px;left:5px;">There is no available data.</span>';
//html = target.append(html);
target.hide();
}

you can show empty data like this
$piedata="[{label:'no data',data:1}]";

Related

Chart.js: Label each dataset

I've been trying to make chart.js have a label for each dataset but the first label is located underneath both datasets and the second on an empty area of the chart.
var powerChart = new Chart(powerCanvas, {
type: "bar",
data: {
labels: ["Volts", "Amperes"],
datasets: [
{
label: "Volts", // This bar should have this label underneath itself
data: [24.78], // Initial value, will be overwritten
},
{
label: "Amperes", // This bar should have this label underneath itself
data: [14.51],
},
],
},
options: {},
});
See https://jsfiddle.net/w20c3tru/2/ for what I have tried and a working example.
Note: I tried to follow
Chart.js Line-Chart with different Labels for each Dataset
but could not see any difference.
Note the comments below:
var powerChart = new Chart(powerCanvas,
{
type: 'bar',
data:
{
labels: ['Volts', 'Amperes'],
datasets:
[
{
label: 'Value', // This is actually the label that shows up when you hover over a bar
data: [24.78, 14.51] // NOTE: Number of labels defined above should equal number of values here
},
]
},
options:
{
}
}
);
Edit:
data:
{
labels: ['Volts', 'Amperes'],
datasets:
[
{
data: [24.78, 14.51], // Volts and amperes, respectively
borderWidth: 1,
borderColor: ['#0000e0', '#e00000'], // Border colors for volts and amperes, respectively
},
]
},
Finally I have it working as I want thanks to a hint by a user who separated the data in x and y sections
Code on jsFiddle
Full working example here:
jsFiddle

Chart.js dinamically populate data in Oracle Application Express

Hi I am suing the library chart.js 2.7 with Oracle application express and I am facing issue with passing data array.
I set up same variable fields to store the the array for the chart, but the chart is not displayed/rendered.
note: P79_.. are item of the page (text field) containing the array from ad hoc queries.
Any suggestions? thanks in advance
here's my code
<script>
var BUDGET1 =[document.getElementById("P79_BUDGET1_AC").value]
var BUDGET2 =[document.getElementById("P79_BUDGET2_AC").value]
var ACTUAL1 =[document.getElementById("P79_ACTUAL1_AC").value]
var ACTUAL2 =[document.getElementById("P79_ACTUAL2_AC").value]
new Chart(document.getElementById("mixed-chart"), {
type: 'bar',
data: {
labels: ["P01", "P02", "P03", "P04","P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12"],
datasets: [{
label: "Plan1",
type: "line",
borderColor: "#c45850",
data: BUDGET1,
fill: false
}, {
label: "Plan2",
type: "line",
borderColor: "#3e95cd",
data: BUDGET2,
fill: false
}, {
label: "Actual1",
type: "bar",
backgroundColor: "#ffbb99",
backgroundColorHover: "#ff9933",
data: ACTUAL1,
}, {
label: "Actual2",
type: "bar",
backgroundColor: "#99ffbb",
backgroundColorHover: "#00ff40",
data: ACTUAL2
}
]
},
options: {
title: {
display: true,
text: 'Plan Trend'
},
tooltips: {
callbacks: {
// this callback is used to create the tooltip label
label: function(tooltipItem, data) {
// get the data label and data value to display
// convert the data value to local string so it uses a comma seperated number
var dataLabel = data.labels[tooltipItem.index];
var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
// make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
if (Chart.helpers.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
// return the text to display on the tooltip
return dataLabel;
}
}
},
legend: { display: true}
}
});
</script>
I do not know if these instructions to create these arrays works. Could try to use console.log in these values to check if works?
var BUDGET1 =[document.getElementById("P79_BUDGET1_AC").value]
var BUDGET2 =[document.getElementById("P79_BUDGET2_AC").value]
console.log(BUDGET1);
console.log(BUDGET2);
var ACTUAL1 =[document.getElementById("P79_ACTUAL1_AC").value]
var ACTUAL2 =[document.getElementById("P79_ACTUAL2_AC").value]
console.log(ACTUAL1);
console.log(ACTUAL2);
*You can execute this code on console. On chrome press F12, go to console.
Look at this post to see how convert a string with commas to array. Convert string with commas to array

Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});

Importing Categorical data from SQL, to C3.js, using JSON

I'm currently working on dynamically building column graphs in MVC, using C3 Charts. While I can bring the data from the database using AJAX/JSON, I am able to bind only the Y-Axis coordinates using the JSON property of C3, not the X-Axis categories.
What I want to do: Build column charts dynamically. For instance, the marks of students of multiple years will be calibrated as (Year 1: 50),(Year 2: 100) and so on, with the first part (category:Year) going on the X-Axis and the numeric part (Marks) going to the Y-Axis. The number of such combinations is dynamic, depending on the user's requirements (brought from the database as two columns, with multiple rows).
Problems I'm running into:
Specifying two different data types in the keys renders the non-numeric part (the category) as a separate series altogether, which I don't want and which isn't even working.
Whatever I do, the X-Axis comes with whole numbers depending on the number of columns visible. I'd like to change that to the actual category names.
Here is what I am doing. I took inspiration from Daniel's method here (https://groups.google.com/d/msg/c3js/RV1X18GZoGY/-p39m9Ngt-gJ)
$.ajax({
url: <Method in Controller here>,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameters),
success: function (data) {
var myData = jQuery.parseJSON(data);
var testJson = $.map(myData, function (item) {
return {
Year: item.Year,
Marks: item.Marks
}
});
var chart = c3.generate({
bindto: '#chart',
size: {
width: 800
},
data: {
json: testJson,
mimeType: 'json',
keys: {
value: ['Marks']
},
}
});
}
});
Looking forward to some assistance. Thanks in advance!
Edit: I want the data to look like this in the end:
Sample Chart
You can try the following code:
var jsonTest = [
{ year: 1, marks: 50 },
{ year: 2, marks: 70 },
{ year: 3, marks: 75 },
{ year: 4, marks: 45 },
];
// The variable name chart will automatically bind itself to an id = chart
var chart = c3.generate({
data: {
type : 'bar',
json: jsonTest,
keys: {
x: 'year',
value: ['marks']
}
},
size: {
width: 400,
},
axis: {
x: {
type: 'category'
}
},
bar: {
width: {
ratio: 0.5
}
}
});
I was getting the following output:
Here's the JSBin example: Bar Chart Example

HighCharts - dynamic graph & no tick mark on the right hand side dual axis

I'm new to high charts.
I'm dynamically making 2 ajax calls(inside getData() Function) and plotting the high chart with 2 series(with 2 y axis).
each ajax call with return the json data.
1st json data (sample)
[{"dt":"May 15, 2000","index":"2,007.030850"},{"dt":"May 16, 2000","index":"2,025.956108"}]
2nd json data (sample)
[{"dt":"May 15, 2000","nav":"145.236000"},{"dt":"May 16, 2000","nav":"146.602974"}]
I'm creating two series with 2 ajax calls. in the 2nd ajax call, i'm dynamically adding a y-axis for the 2nd series data.
$(document).ready(function() {
function getData() {
var chart = Highcharts.charts[0];
/* 1st Ajax Call to get the json data to plot the first series */
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Six/TSServlet?file=ivv-sixIshareFundsHistoryIndex.json',
data: '',
async: false,
success: function(data) {
var categories1 = [];
var seriesData1 = [];
var yaxis;
$.each(data, function(i, e) {
categories1.push(e.dt);
/* below step to remove , is not important, done for my program */
yaxis = parseFloat(e.index.replace(/,/g, ''));
seriesData1.push(yaxis);
})
// add x-axis catagories
chart.xAxis[0].update({
categories: categories1,
tickInterval: 150
}, true);
// add the 1st series
chart.series[0].setData(seriesData1);
}
});
/* 2nd Ajax Call to get the json data to plot the second series */
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Six/TSServlet?file=ivv-sixIshareFundsHistoryNav.json',
data: '',
async: false,
success: function(data) {
var categories2 = [];
var seriesData2 = [];
var yaxis;
$.each(data, function(i, e) {
categories2.push(e.dt);
/* below step to remove , is not important, done for my program */
yaxis = parseFloat(e.nav.replace(/,/g, ''));
seriesData2.push(yaxis);
})
/* This is the problem area, dynamically adding a dual y axis for the 2nd series */
chart.addAxis({ // Secondary yAxis
id: 'NAV-Series-Axis',
title: {
text: 'NAV Series'
},
lineWidth: 2,
lineColor: '#08F',
opposite: true
});
// add the 2nd series
chart.addSeries({name: "NAV Series",yAxis: 'NAV-Series-Axis',data: seriesData2});
}
});
} //getdata function ends here .............
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
renderTo: 'container',
events: {
load: function() {
var series = this.series[0];
getData();
}
}
},
title: {
text: 'Six Share Funds History'
},
labels: {
formatter: function() {
return this.value + ' %';
}
},
xAxis: {
tickLength: 10
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' + this.x + '<br/>' + Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
"Name": []
}]
});
});
});
My issue is i'm getting 2 axis for 2 series graph, but no tick marks on the right hand side y-axis. how to solve this issue? ideally i should see 100(one tick mark), 200 (one tick mark) etc on the right hand side blue bar(just like left hand side y-axis has 500,1000 etc)
Please see the screen shot, i dont see the tick marks on the right hand side blue bar (for the 2nd series graph)
Edited to add jsp:
<div id='TimeSeriesId'>
<div id="container" style="width: 100%; height: 600px;"></div>
</div>
You can add several Y-axes simply by making yAxis an array with more than 1 element. Each can have all of the usual axis attributes (see highcharts API).
yAxis: [{ // Primary yAxis
labels: { ...
},
title: { ...
},
opposite: true
}, { // Secondary yAxis
title: { ...
},
labels: { ...
}
}, { // Tertiary yAxis
title: { ...
},
labels: { ...
},
opposite: true
}],
...
To dynamically add them, use chart.yAxis = new Array(); chart.yAxis[1].title = ... etc.

Categories

Resources