getting data from php page and I am passing chartData array to pie(title,chartData) function as second parameter. Now chartData array is placing in data: [ chartData ] but it not working. But when I add manually with key then It work data: [ chartData[0],chartData[1], ]. But I don't want to mention it manually with key. I want to arry work automatically like data: [ chartData ]
What I have to do?
function createChart(chart) {
if ( chart == 'pie' ) {
var title = $("#chart-title").val();
/***************** Data Elements ****************/
var totalElements = $("#addMoreRowNo").val();
var chartData = new Array();
for(var j = 1; j <= totalElements; j++)
{
var key = $("#chart-pie-text_"+j).val();
var value = $("#chart-pie-percentage_"+j).val();
var data = [key, parseFloat(value)];
chartData[j-1] = data;
}
/***************** Data Elements ****************/
pie(title,chartData);
}
}
function pie(title,chartData) {
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: title
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
chartData
/*chartData[0],
chartData[1],*/
//['Active Postings (13)', 20.00],
]
}]
});
}
I'm pretty sure your problem can be solved by replacing
data: [
chartData
]
with
data : chartData
The way you're writing it, you're defining data as an array containing chartData, which itself is an array. The way you indicate you're testing it, though, is to get the items out of chartData and put each item into data, which results in a different structure.
Related
I have one Json with multiple array and foreach array I want to create Pie chart, but I don't know how to do it.
This is the array thet I have. And this is what I tried :
function Pie() {
$.getJSON("/Admin/Attivita/OreOggi", function (data) {
console.log(data);
var oreTecico = [];
var oreTecico = [];
var oreMalatia = [];
var oreStraordinario = [];
var oreInfortunio = [];
var oreFerie = [];
for (var i = 0; i < data.length; i++) {
nomeTecnico.push(data[i].nome);
oreTecico.push(data[i].odinario);
oreMalatia.push(data[i].malatia);
oreStraordinario.push(data[i].straordinario);
oreInfortunio.push(data[i].infortunio);
oreFerie.push(data[i].ferie);
};
// Build the chart
Highcharts.chart('zdravko', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Ore segnate oggi'
},
tooltip: {
pointFormat: '<b>{point.name}</b>: {point.y:.1f} h.'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: nomeTecnico[0],
colorByPoint: true,
data: [{
name: '',
y:0,
sliced: true,
selected: true
}, {
name: 'Odinario',
y: oreTecico[0]
}, {
name: 'Malatia',
y: oreMalatia[0]
}, {
name: 'Straordinario',
y: oreStraordinario[0]
}, {
name: 'Infortunio',
y: oreInfortunio[0]
}, {
name: 'Ferie',
y: oreFerie[0]
}]
}]
});
});
}
It shows only the last "data". I want to make fo each array one pie. If i have 100 arrays I want 100 pies.
UPDATE:
I added this :
data.forEach(function (el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('zdravko').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
The chartData is array of undefined objects.
Is it possible to make for or foreach inside Highcharts?
You need to use the Highcharts.chart method in a loop, for example:
var data = [{
data1: 12,
data2: 25
}, {
data1: 67,
data2: 11
}];
data.forEach(function(el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('container').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
Live demo: http://jsfiddle.net/BlackLabel/x95pbw7j/
API Reference: https://api.highcharts.com/class-reference/Highcharts#.chart
Got a column called ChartData in database with a string value of 4,11,25,36,50. Trying to assign this value to a hidden variable so JS can read the value of this and put this value in the data option using high charts. I have console.log the variable and looks like its appearing as a string rather than an array when being parsed across the server side to the client side.
C# code
string str = reader["ChartData"].ToString();
string[] strList = str.Split(','); //seperate the hobbies by comma
// convert it in json
dataStr = JsonConvert.SerializeObject(strList, Formatting.None);
hiddenvariable.Value = dataStr;
JS code:
function CreateBoxPlot() {
var hv = $('#hiddenvariable').val();
alert(hv); //["40","61","65","74","77"]
var chart;
var titleText = 'Test Chart Title';
var subTitleText = 'Test Chart Subtitle';
var type = 'boxplot';
var data = hv;
console.log(data); //["40","61","65","74","77"]
$(function () {
$('#container').highcharts({
chart: { type: type, inverted: true },
title: { text: titleText },
subtitle: { text: subTitleText },
legend: { enabled: false },
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({ data: data });
});
}
However when i hardcode data to the below value this works. How do i format this correctly when its parsed over to the JS side:
var data = [[40,61,65,74,77]]
You have to convert the string '["40","61","65","74","77"]' to js array with numbers. To make it work on each browser you can follow this approach:
Parse the string to js array using JSON.parse()
Loop through the created array and convert each element to number:
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
Code:
$(function() {
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
$('#container').highcharts({
chart: {
inverted: true
},
legend: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({
data: data
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
Demo:
https://jsfiddle.net/BlackLabel/ay1xmgoc/
Taking reference from the comments, add this to your code and then try.
var data = hv.map(function (element) {
return +element;
});
I want to use json data to construct mutipal pie charts. And put the pie chart inside class container, so for example:
data.data[0].usedPercentage=0,
data.data[1].usedPercentage=20,
data.data[2].usedPercentage=0,
the output pie chart should display like 0%, 20%, 0% ,
but now they display the same all in 0%, could anybody give some clues about that? Thanks a lot
$.ajax({
type: "GET",
url: 'http://XXX.XXX.XXX.XX',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var used = new Array();
for (var i = 0; i < data.data.length; i++) {
used[i]=data.data[i].usedPercentage;
pieIndex(used[i]);
projectList +="<div class='container'>pie</div>"
function pieIndex(used){
$(function () {
// Using classes to select multiple containers
var $containers = $(".container");
// You just set the configuration object once
var chartConfig = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'precentage',
colorByPoint: true,
data: [{
name: 'Unused',
y: 100-Number(used),
color: '#eeeeee',
sliced: true,
selected: true
}, {
name: 'Used',
y: Number(used),
color: '#f34s12',
selected: true
}]
}]
};
$containers.each(function() {
$(this).highcharts(chartConfig);
});
});
}
},
error:function(){
alert("connection error");
}
});
});
Each chart need a unique id on the container. Looks like you are overwriting those containers with the last chart. Try using a different id on each container div. For example:
projectList +="<div id='pie-chart-container-" + i + "' class='container'>pie</div>"
Pie Chart looks like this:
Data is there in JSON:
EDIT
From console:
When i tried it with type of "bar" or "column" chart it works fine.
Still new to this and really appreciate your help, folks!
Django version: 1.10
Python version: 3.6
chartViewHigh.html
{% block main %}
<h1 align="center">Analysis</h1>
{% block content %}
<div id="container" style="width:50%; height:400px;"></div>
{% endblock %}
{% block extrajs %}
<script>
var endpoint = '/api/chart/data/';
var labels = [];
var defaultData = [];
var labels2 = [];
var defaultData2 = [];
$.ajax({
method: "GET",
url: endpoint,
/**
* #param data
* #param data.labels
* #param data.default
* #param data.default2
*/
success: function (data) {
labels = data.labels;
defaultData = data.default;
labels2 = data.labels2;
defaultData2 = data.default2;
setChart()
},
error: function (error_data) {
console.log("error");
console.log(error_data)
}
});
function setChart() {
$(document).ready(function() {
var chart = {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
};
var title = {
text: 'Total'
};
var tooltip = {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
};
var plotOptions = {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}%</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
};
var series= [{
type: 'pie',
name: 'Group share',
data: [
{ name: 'Board', y: defaultData },
{
name: 'Member',
y: defaultData2,
sliced: true,
selected: true
}
]
}];
var json = {};
json.chart = chart;
json.title = title;
json.tooltip = tooltip;
json.series = series;
json.plotOptions = plotOptions;
$('#container').highcharts(json);
});
views.py
class ChartData(APIView):
def get(self, request, format=None):
qs_count = Administrator.objects.filter(association=self.request.user.association).count()
qs_count2 = Member.objects.filter(association=self.request.user.association).count()
labels = ["Members"]
default_items = [qs_count2]
labels2 = ["Board"]
default_items2 = [qs_count]
data = {
"labels": labels,
"default": default_items,
"labels2": labels2,
"default2": default_items2
}
return Response(data)
The data array has incorrect format. y values must be numbers, you set them as an array.
Change series variable to:
var series= [{
type: 'pie',
name: 'Group share',
data: [{
name: 'Board',
y: defaultData[0] },
{
name: 'Member',
y: defaultData2[0],
sliced: true,
selected: true
}
]
}];
Or send those values as a single number instead of an array.
You look to be missing in your chart section a declaration of a pie chart.
var chart = {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie' // this is missing.
};
Have not been able to run your code to test but fingers crossed this sorts it for you.
The chart calls in JSON file that hold a string(color) and integer(count). I want to change the color of the each slice in a pie chart according to what the JSON file holds. So if the JSON file is [["Green",1],["Red",44],["Yellow",30]] I would like the the "Green" slice to have the color of green...etc. I've tried:
plotOptions: {
pie: {
//colors: ['#739600', '#bb0826', '#fcc60A'],
formatter: function () {
if ('Green' === this.value) {
return '<span style="fill: #739600;">' + this.value + '</span>';
}
else if ('Red' === this.value) {
return '<span style="fill: #bb0826;">' + this.value + '</span>';
}
else if ('Yellow' === this.value) {
return '<span style="fill: #fcc60A;">' + this.value + '</span>';
}
}, ...
It's not working how I expected. http://jsfiddle.net/LazerickL/bvaxmcLr/4/
Any help would be appreciated.
UPDATE
I had to restructure my JavaScript to call $.getJSON function. So, how would I proceed to implement the color slices for my latest code below? Thanks for any help!
$(document).ready(function() {
var options = {
chart: {
renderTo: 'containter',
defaultSeriesType: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: null
},
credits: {
enabled: false
},
tooltip: {
pointFormat:
'{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
//colors: ['#739600', '#bb0826', '#fcc60A'],
allowPointSelect: true,
cursor: 'pointer',
depth: 30,
showInLegend: true,
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.point.y;
}
}
}
},
series: [{
type: 'pie',
name: 'Amount',
data: []
}]
}
$.getJSON("js/test.json", function (json) {
options.series[0].data = json;
var chart = new Highcharts.Chart(options);
});
});
To set your colors on your pies you'll need to update how you're pushing things into the data array to include the color of your pie. I accomplish this by adding a field to your data array but you could use an if statement like you had in the function if you prefer.
Here is an updated fiddle: http://jsfiddle.net/bvaxmcLr/8/
Also, your placement of the formatter function is invalid. That formatter javascript only applies to data labels as far as I know.
The important change from your script is removing the formatter function and updating to this to push the color value onto each data point:
var data={'d':[
{'Status_Color':'Green', 'Corrective_Action_ID':3},
{'Status_Color':'Red', 'Corrective_Action_ID':5},
{'Status_Color':'Yellow', 'Corrective_Action_ID':10},
]};
$.each(data.d, function (key, value) {
var colorVal = '';
if(value.Status_Color=='Green'){
colorVal = '#739600';
}
if(value.Status_Color=='Red'){
colorVal = '#bb0826';
}
if(value.Status_Color=='Yellow'){
colorVal = '#fcc60A';
}
var temp = {name:value.Status_Color, color:colorVal, y:value.Corrective_Action_ID};
options.series[0].data.push(temp);
})
Here is the whole script:
$(function () {
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: null
},
subtitle: {
text: null
},
credits: {
enabled: false
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y:.1f}</b>'
},
plotOptions: {
pie: {
depth: 45,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Amount',
data: []
}]
}
var data={'d':[
{'Status_Color':'Green', 'Corrective_Action_ID':3},
{'Status_Color':'Red', 'Corrective_Action_ID':5},
{'Status_Color':'Yellow', 'Corrective_Action_ID':10},
]};
$.each(data.d, function (key, value) {
var colorVal = '';
if(value.Status_Color=='Green'){
colorVal = '#739600';
}
if(value.Status_Color=='Red'){
colorVal = '#bb0826';
}
if(value.Status_Color=='Yellow'){
colorVal = '#fcc60A';
}
var temp = {name:value.Status_Color, color:colorVal, y:value.Corrective_Action_ID};
options.series[0].data.push(temp);
})
chart = new Highcharts.Chart(options);
});
});