Highchart Pie Chart shows "slice 0.0%" when loading data from csv - javascript

I try to load data from CSV data to create a pie chart.
There always slice showing "slice:0.0%". However, in my CSV data, there is no such a data called slice. I'm wondering if this is because the highchart's default setting or it's because I used the wrong way to read CSV data file.
Jsfiddle_code
Below is photo of the chart.
var pie_bl = Papa.parse(document.getElementById('pie_bl').innerHTML);
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
data: {
rows: pie_bl.data
},
title: {
text: 'Pie Chart_csv'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
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'
}
}
}
},
});
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="https://rawgit.com/mholt/PapaParse/master/papaparse.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<pre id="pie_bl" style="display:none">Category,Allocation
a,0.45,
b,0.5,
c,1.25,
d,0.15,
e,0.1,
f,0.55,
</pre>

Your CSV data in <pre> tag is ending with a , and a new-line. In CSV this will be treated as another entry. This is why it is showing Slice: 0.0.
By default Highcharts assigns the label as Slice and value as 0 if not mentioned. So your <pre> tag should look something like this
<pre id="pie_bl" style="display:none">
Category,Allocation
a,0.45
a,0.45,
b,0.5,
c,1.25,
d,0.15,
e,0.1,
f,0.55</pre>
Update your fiddle here

Your values will be with proper comma
<pre id="pie_bl" style="display:none">Category,Allocation,
a,0.45,
b,0.5,
c,1.25,
d,0.15,
e,0.1,
f,0.55,</pre>
Fiddle

Related

How to show selected date on line chart plot with x axis in High chart if I have multiple value for single date

I am using Highchart , I am new for it , I need to show line chart when i have a selected date array and every date have multiple value.
For Example I have
date=[2022-01-02,2022-01-07,2022-01-10]
and
Data=[[1,2,3],[3,5,4],[6,3,4]]
I have some references but for column and single data : https://jsfiddle.net/50e1nbac/4/
enter image description here
In above picture I just need to mentioned date from list on X-axis.
For showing observation scatter series will be fit to visualize it how many times the action has occurred. You can insert the dates as categories, the points will refer to them.
var dates = ["2019-06-14 17:00:00", "2019-06-14 17:01:00", "2021-04-13 06:15:00"];
Highcharts.chart('container', {
title: {
text: 'Scatter plot with regression line'
},
xAxis: {
type: 'datetime',
categories: dates
},
yAxis: {
min: 0
},
series: [{
type: 'line',
name: 'Regression Line',
data: [
[0, 1.11],
[5, 4.51]
],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
}, {
type: 'scatter',
name: 'Observations',
data: [1, 1.5, 2.8, 3.5, 3.9, 4.2],
marker: {
radius: 4
}
}]
});
#container {
height: 400px;
}
.highcharts-figure,
.highcharts-data-table table {
min-width: 310px;
max-width: 800px;
margin: 1em auto;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<figure class="highcharts-figure">
<div id="container"></div>
</figure>
Demo: https://jsfiddle.net/BlackLabel/9r07asom/
https://www.highcharts.com/docs/chart-and-series-types/scatter-chart
https://api.highcharts.com/highcharts/xAxis.categories

HighCharts add space to Y-Axis Label gutter

I have created a chart using the HighCharts javascript library, the problem I have is that my y-Axis labels are cut by the Y-Axis vertical line. I would like to add more space in the y-axis label gutter area to allow for the labels to be fully visible and so i can add some annotations to the in that area, see image below:
Ideally I would like to add 40px, to the Y-Axis gutter. I have read through the api reference and tried using "yAxis.labels.padding", "yAxis.margin" and "yAxis.offset".
My code is as follows:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
#container {
height: 400px;
width: 350px;
}
.highcharts-tick{display: none;}
.highcharts-grid-line{opacity: 0.2}
</style>
</head>
<body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script src="https://code.highcharts.com/stock/modules/accessibility.js"></script>
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id=container2></div>
<script type="text/javascript">
$(function() {
const options = {
chart: {
backgroundColor: '#1B191B', // Background Color
type: 'line',
zoomType: "",
},
rangeSelector : {
enabled: false,
selected : 2,
inputEnabled: false
},
title: {
text: 'APPLE INC', // Title of the Chart
align: 'left',
style: {
color: '#dedbde', // Custom CSS for the title
fontWeight: 'bold'
}
},
scrollbar: { enabled: false },
exporting: {
enabled: false
},
yAxis: {
lineWidth: 2,
tickWidth: 1,
labels: {
style: {
color: '#dedbde'
},
align: 'right',
},
opposite: true,
offset: -1
},
xAxis: {
labels: {
style: {
color: '#dedbde'
}
},
gridLineWidth: 1,
},
navigator: {
enabled: false
},
series: [{
name: 'AAPL Stock Price',
data: [],
type: 'areaspline',
threshold: null,
color: '#5861B3',
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
}
}]
}
const url = 'https://demo-live-data.highcharts.com/aapl-c.json'
const chart = Highcharts.stockChart('container', options)
$.getJSON(url, function(data) {
chart.series[0].setData(data)
// Execute callback
if (chart.options.chart.events && chart.options.chart.events.dataLoad) {
const dataLoad = chart.options.chart.events.dataLoad.bind(chart)
dataLoad(data)
}
})
})
</script>
</body>
</html>
Been banging my head around this for while, but I cant seem to figure it out any help would be very much appreciated. Thanks
In Highstock, the yAxis is inverted by default, so aligning the labels is reversed as well.
The only thing you need to change is setting yAxis.labels.align to 'left'.
Demo:
https://jsfiddle.net/BlackLabel/10ae8g9d/

Plotting data using highcharts piechart in flask web application

I am trying to plot pandas dataframe from a python function and display it on a web server using Highcharts pie chart. I can get the data from the function to the web server as json data through flask. but when I want to display it the chart is empty. Through the web console I also made sure that the data format going into the Highcharts is correct but still nothing.
Here I am retrieving the panda dataframe and sending it to the web server through flask:
actype_json = actype.to_json(orient = 'records')
#app.route('/data/airport', methods = ['GET'])
def broadcast_data():
return eval(json.dumps(actype_json))
#app.route('/')
def plotgraph():
return render_template('airport.html')
On my HTML file, I tried to use AJAX to call for the data and plot it in a Highcharts Pie Chart:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<script>
function GetUpdatedData(){
$.ajax({
url: "/data/airport",
})
.done(function( data ) {
console.log( data );
DrawGraph(data);
});
}
function DrawGraph(dataset) {
// Radialize the colors
Highcharts.setOptions({
colors: Highcharts.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
})
});
// Build the chart
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares in January, 2018'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
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'
},
connectorColor: 'silver'
}
}
},
series: [{
name: 'Aircraft',
data: [dataset]
}]
});
setTimeout(GetUpdatedData, 1500);
}
</script>
</body>
</html>
This is the screenshot of the Highcharts Pie Chart that I am seeing:
The response tab is showing the format of the data trying to be plotted on Highchart. Any advice will be very helpful. Thanks!
You've made a simple mistake when adding data to series.data array. Note that your data is actually a correct Highcharts data array with point objects inside:
data:
[{
"AC TYPE": "B773",
"y": 35
}, {
"AC TYPE": "B77W",
"y": 16
}]
However, you've added this array inside another one like that:
series: [{
name: 'Aircraft',
data: [dataset]
}]
This gives you an invalid data format with two nested arrays:
series: [{
name: 'Aircraft',
data: [[{
"AC TYPE": "B773",
"y": 35
}, {
"AC TYPE": "B77W",
"y": 16
}]]
}]
Remove the wrapping array and the chart should be rendered correctly.
Demo:
https://jsfiddle.net/BlackLabel/49rhpmyg/

Highcharts - Display legend for Pie chart in two columns

I have been using Highcharts(v2.1.9) to generate some pie charts. The charts are generated quite well, however I am having some problems with displaying the legend.
The legend shows in vertical view, but instead of all the legend items showing, some are hidden. I believe this is due to the navigation option being automatically enabled, which pages all of the other legend items that do not fit within the container.
Instead of paging the rest of the legend items, I want to show them in a second column, side by side with the first column.
This data is dynamic so the number of legend items/pie sectors may change over time. The solution must be able to handle more than two columns if the sectors increase.
I think one way to turn off the navigation option is to use the useHTML: true option but I haven't been able to style it in the way that I want.
Here is the fiddle: http://jsfiddle.net/7fb3x9ys/
$(function () {
$(document).ready(function () {
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
borderWidth: 0,
width: 800,
height: 280
},
credits: {
enabled: false
},
legend: {
borderWidth: 0,
labelFormatter: function() {
var total = 0, percentage;
$.each(this.series.data, function() {
total+=this.y;
});
percentage=((this.y/total)*100).toFixed(2);
return '<span style="color:#000000,font-size:12px !important;"><b>'+ this.name + '</b></span><br/><span style="color:#000000,font-size:12px !important;">'+percentage+'%</span>';
},
verticalAlign: 'middle',
x:185,
y:0,
layout: 'vertical',
width: 600,
height:280,
itemWidth: 600,
symbolWidth: 7,
symbolHeight: 28
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
size: 275,
center: ["16%", "50%"],
dataLabels: {
enabled: false,
},
showInLegend: true,
minSize: 130,
colors: [
'#7DA0B0',
'#9264AA',
'#4F2A72',
'#9A3968',
'#BF5269',
'#E16553',
'#E3985E',
'#E4BF80',
'#75C494',
'#52584B'
]
}
},
series: [{
type: 'pie',
name: 'Sector',
data:{"data":[["ENERGY",17.4],["FINANCIALS",15.1],["CONSUMER STAPLES",14.9],["UTILITIES",14.88],["MATERIALS",7.59],["REAL ESTATE",7.24],["TELECOMMUNICATION SERVICES",7.08],["CONSUMER DISCRETIONARY",6.95],["INDUSTRIALS",5.28],["HEALTH CARE",2.64],["CASH",0.95]]}.data
}]
});
});
});
I want to thank all responses in advance. I have been stuck on this for a few days now and any help would be greatly appreciated.
You can try laying out the legends horizontally and setting itemWidth to something greater than 80. That worked for me.
Example:
legend: {
itemWidth: 80
}

Highcharts column fit/adjust on chart

I write because I go back to being stuck in a problem with Highcharts. I have a monthly chart that works fine except for one thing. The zoom level. The X axis is always shown me a value of 0 (today), so that the zoom level is incorrect. I am attaching a picture to try to explain it better. I need this column set in the graph.
I appreciate your help! Thank you!
The json returned by PHP is (correct results):
{"data":[[1401580800000,2],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0]]}
And Javascript file:
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsGrupo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: tituloMes
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d/%m/%Y',new Date(this.x)) + '<br/>' +'Alarmas: ' + this.y
}
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
day: '%e. %b',
labels: {
style: {
width: '200px','min-width': '100px'
},
useHTML : true,
}
}
},
yAxis: {
title: {
text: 'Total alarmas'
},
allowDecimals: false,
min: 0
},
series : [{
showInLegend: false,
name : 'Grafica Mensual',
type : 'column',
data: data.data,
dataLabels: {
enabled: true,
rotation: 0,
color: '#000000',
align: 'center',
y: 0,
style: {
fontSize: '14px',
fontFamily: 'Verdana, sans-serif',
}}
}]
});
}); ///cierra get
EDIT: I need a graphic for month (user select), but, the white area and Xaxis only appers info for the month selected. The PHP file return a correct JSON chain, but highcharts not fit the columns fine. Sorry for my english!
The problem is with your JSON, where you have duplicated values for the same timestamp. Just remove them.
Then! You have unsorted data, it should be sorted ascending by timestamp.
After fixed, it works fine, see: http://jsfiddle.net/4nCx3/
var data = {
"data": [
[1400025600000, 0],
[1401580800000, 2]
]
};

Categories