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/
Related
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
i am trying to put labels on x-axis for the charts mentioned below.
even the labels that i want to display are taken from the database and displayed. for each value of y-axis there is a repective x-axis. so i want like when i hover on the point x-axis value : y-axis value. it should appear like this.
If anyone had tried this earlier, please help.
Highcharts.stockChart('container', {
scrollbar: {
barBackgroundColor: 'gray',
barBorderRadius: 7,
barBorderWidth: 0,
buttonBackgroundColor: 'gray',
buttonBorderWidth: 0,
buttonArrowColor: 'yellow',
buttonBorderRadius: 7,
rifleColor: 'yellow',
trackBackgroundColor: 'white',
trackBorderWidth: 1,
trackBorderColor: 'silver',
trackBorderRadius: 7
},
rangeSelector: {
selected: 1
},
series: [{
name: 'USD to EUR',
data: usdeur
}]
});
<div id="container" style="height: 400px; min-width: 600px"></div>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript" src="https://www.highcharts.com/samples/data/usdeur.js"></script>
Use tooltip's formatter (Highcharts API here)
tooltip: {
formatter: function() {return this.x+" : "+this.y}
}
Assuming you have the names you want to give to the x-Axis in an array, this code should work:
Javascript:
var namesArray = ["Name1", "Name2", "Name3", "Name4"]
Highcharts.stockChart('container', {
tooltip: {
formatter: function () {
var s = '';
$.each(this.points, function () {
s += namesArray[this.series.data.indexOf(this.point)] +" : "+this.y;
});
return s;
}
},
rangeSelector: {
selected: 1
},
series: [{
name: 'USD to EUR',
data: [3, 5, 6, 7]
}]
});
Please notice I added namesArray as an example here.
What the tooltip function does is the following:
it declares a String
it loops through all of your Highstock points
for each point, it gets the index of the point in series.data and gets the same index from namesArray. This should achieve the thing you need.
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
I'm trying to plot some data I have in my database. I'm following this jsfiddle for the structure. However even though I manage to get the data correctly from my API, the chart shows up but no data is plotted.
My app.js looks something like this:
// Load Sessions
var sessions = new Vue({
el: '#sessions',
delimiters: ["v{","}"],
data: { date:'', sessions:'', json:'', timestamp:''},
methods: {
loadSessions: function(){
var vm = this
axios.get('/api/v1/metrics/')
.then(function(response) {
vm.json = response.data
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'Session Over Time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Sessions'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
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')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'Sessions',
data: vm.json
}]
});
})
}
}
})
The vm.json file looks like this:
[ { "date": "2017-01-02", "timestamp": 1483401600, "sessions": 1100 }, { "date": "2017-01-03", "timestamp": 1483488000, "sessions": 1159 }, { "date": "2017-01-04", "timestamp": 1483574400, "sessions": 1084 }]
And I load vue in my html with a simple:
<div id='sessions'>
<a class="button is-primary" #click='loadSessions'>Load Sessions</a>
<!-- Just to test that data is loaded correctly from API -->
<ul style="margin-left: 20px;">
<li v-for="item in json">
<b>Date: </b> v{item.date} <br />
<b>Sessions:</b> v{item.sessions} <br />
<b>Timestamp:</b> v{item.timestamp}
</li>
</ul>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</div>
Now I think that my problem is on formatting the json, isn't it? The on in the jsfiddle example looks a bit different. How can I get my data to show up?
You can convert your data into the format that is shown in the example.
series: [{
type: 'area',
name: 'Sessions',
data: vm.json.map(d => [new Date(d.date).getTime(), d.sessions])
}]
I converted your date properties to Javascript Date objects in order to use getTime because your timestamp property, where ever it came from, is not a proper Javascript timestamp.
Example.
I'm attempting to use Highcharts Series function to create a combination bar/line chart, but I'm having trouble just getting the series to display. There's nothing in the API about how to format data from Google Spreadsheets when using series so I took a stab at it and the chart does not display:
$(function() {
Highcharts.setOptions({
chart: {
backgroundColor: '#fff',
shadow: false,
width: null,
height: null
}
});
$('#ms-96-enrollment').highcharts({
series: [{
type: 'bar',
data: [{
googleSpreadsheetKey: '1Nx8zcIi0ULxytLmra0A9N11-llzJCDVH2-7SbK_k5-U',
startColumn: 0,
endColumn: 1,
startRow: 0,
googleSpreadsheetWorksheet: 7
}],
}]
});
});
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
</head>
<div>
<div id="ms-96-enrollment"></div>
Highcharts is a little bit misleading having two "data"s - in series and on top level. The first is used for javascript point arrays while the later is for facilitating adding existing datasets (http://api.highcharts.com/highcharts#data)
Thus for Google Spreadsheets
$('#ms-96-enrollment').highcharts({
chart: {
type: 'bar'
},
data: {
googleSpreadsheetKey: '1Nx8zcIi0ULxytLmra0A9N11-llzJCDVH2-7SbK_k5-U',
startColumn: 0,
endColumn: 1,
startRow: 0,
googleSpreadsheetWorksheet: 7
},
title: {
text: 'My google data'
},
yAxis: {},
xAxis: {
labels: {
enabled: true,
}
}
});
Here's the sample based on your data http://plnkr.co/edit/aIqMVcaeyYEbHcdxoMaT
UPDATE
If you need to show multiple series add extra columns and specify series:
data: {
googleSpreadsheetKey: '1Nx8zcIi0ULxytLmra0A9N11-llzJCDVH2-7SbK_k5-U',
startColumn: 0,
endColumn: 2,
startRow: 0,
googleSpreadsheetWorksheet: 7
}
...
series: [{
type: 'bar'
}, {
type: 'line'
}]
Here's the updated sample http://plnkr.co/edit/UQprlugBtUXQX9OffUm4?p=preview