Highcharts - Exporting Module - javascript

I am using highcharts to generate graphical data pulled from a database.
I am having trouble using the exporting module. I have included the exporting property:
exporting{
enabled:true
}
but the buttons do not appear...
I have also linked the exporting.js to the file too...no buttons appear..
Has anyone else had this issue?
EDIT:
Here is the code:
$.ajax({
type:"POST",
url: "retrievechartdata.php",
data: {questionId:qId, questionIdTwo:qIdTwo, title:title, titleTwo:titleTwo, from:from, to:to},
dataType: "json",
success: function(data) {
//$("#response").html("<div class='successMessage'>"+ data.valuesTwo +"</div>");
var maxY = parseInt(data.max) + 1;
var minY = parseInt(data.min);
if(minY > 0){
minY = 0;
}else{
minY -= 1;
}
var cdata = new Array();
cdata= data.values.split(',');
for(var i=0;i<cdata.length;i++)
{
cdata[i]= parseInt(cdata[i]);
}
var leg = false;
var title = data.questionTitle;
if(data.valuesTwo != "FALSE"){
leg = true;
title += " & "+data.questionTitleTwo;
var cdataTwo = new Array();
cdataTwo = data.valuesTwo.split(',');
for(var i=0;i<cdataTwo.length;i++)
{
cdataTwo[i]= parseInt(cdataTwo[i]);
}
}
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'x',
spacingRight: 20
},
credits: {
enabled: false
},
title: {
text: title
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Drag your finger over the plot to zoom in'
},
xAxis: {
type: 'datetime',
maxZoom: 14 * 24 * 3600000, // fourteen days
lineWidth: 1,
lineColor: '#999999',
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: data.questionTitle
},
labels: {
y: 2
},
lineWidth: 1,
lineColor: '#999999',
gridLineWidth: 1,
gridLineColor: '#eaeaea',
min: minY,
max: maxY,
startOnTick: false,
showFirstLabel: false
},
tooltip: {
shared: true
},
legend: {
enabled: leg
},
plotOptions: {
area: {
Color: {
linearGradient: [0, 0, 0, 600],
stops: [
[0, 'rgb(69, 114, 167)'],
[1, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: [{
type: 'spline',
name: data.questionTitle,
pointInterval: 24 * 3600 * 1000,
pointStart: Date.UTC(data.year, data.month, data.day),
data: cdata,
lineColor: '#f6a828',
color: '#418ed6'
},
{
type: 'spline',
name: data.questionTitleTwo,
pointInterval: 24 * 3600 * 1000,
pointStart: Date.UTC(data.year, data.month, data.day),
data: cdataTwo,
lineColor: '#808080',
color: '#ff0000'
}],
exporting: {
enabled: true
}
})

Which version of Highcharts you are using? Which version of jQuery?
Currently is the v2.1.6, I recommend you use the latest release because they are continuously fixing bugs, adding new functionality, etc.
Prior to v2.0 there is no support to the exporting feature
The only things you need to do in order to bring the exporting module working are:
1- First: Add the js script after the highcharts script, like this:
...
<script type="text/javascript" src="../js/highcharts.js"></script>
<!-- 1b) Optional: the exporting module -->
<script type="text/javascript" src="../js/modules/exporting.js"></script>
...
The exporting module is enabled by default, so there is no need to have the code you posted, so you can remove it:
exporting{
enabled:true
}
2- Second: Be sure to publish the exporting-server/index.php file correctly.
Here you have what the official documentation reads about the exporting module installation:
Exporting module
From version 2.0 an exporting module is available for Highcharts, which allows users to download images or PDF's of your charts. This module consists of an extra JavaScript file, exporting.js, and a web service or server module written in PHP. Highslide Software offers the exporting web service free of charge. If you include the exporting module in your charts, two buttons will appear in the upper right. One button prints the chart, which is done on the client side only. The other button handles exporting. By default, an SVG representation of the chart is sent by POST to http://export.highcharts.com, where it is converted using Apache's Batik converter to PDF, PNG or JPEG.
See the navigation and exporting reference items for a full documentation for the options available. Also see under "Methods and Properties" in the reference for members releated to exporting.
Here you can see the configuration options regarding the exporting module: http://www.highcharts.com/ref/#exporting
Hope it helps you.

Make sure the script tag has
type="text/javascript"

Related

Why would the label of the vertical axis only show after the button is clicked?

I am working on a website which needs to show something on the chart (highchart) upon clicking of a button.
The issue is: when the page is first loaded, the label on the vertical axis can not be seen, no matter how big I set the margin for the chart. However, after the button is clicked for the first time, the labels can be seen and remains so.
There was no such problem before I set "reversed", "opposite" for xAxis and "reversed" for yAxis as true.
What causes this phenomenon and how can I solve this?
See the JSFiddle for detail. (There are some logic mistakes in the code which is irrelevant for my question.)
I just discovered that when I first load the JSFiddle, the vertical axis of the graph shows up with label; but when I click on "Run" additionally, the graph is refreshed with a vertical axis without label. Maybe I can simulate certain process which takes place when a JSFiddle is loaded to make sure that the vertical axis of the graph shows up with labels. But I am not sure how to do that.
Browser: Google Chrome Version 69.0.3497.92 (Official Build) (64-bit) (up to date)
My OS: Windows 10
Code for the generation of the chart:
function createColumnHorizChart(argMinY = minYAxis, argMaxY = maxYAxis) {
var chart = new Highcharts.Chart({
chart: { //not to be changed lightly
renderTo: 'contr2',
type: 'bar',
width: 749,
marginTop: 5,
marginLeft: 1,
marginRight: 90,
marginBottom: 55
},
colors: [
'#0000ff'
],
title: {
text: null
},
exporting: {
enabled: false
},
legend: {
enabled: false
},
credits: {
enabled: false
},
xAxis: {
categories: ['smaller than 100', '100 - 110', '110 - 120', '120 - 130', '130 - 140', '140 - 150', 'bigger than 150'],
gridLineWidth: 1,
startOnTick: true,
title: {
text: 'Money Unit (MU)'
},
opposite: true,
reversed: true
},
yAxis: {
reversed: true,
min: 0,
max: 15,
tickInterval: 5,
title: {
text: 'Frequency',
}
},
tooltip: {
positioner: function(boxWidth, boxHeight, point) {
return {
x: point.plotX - 50,
y: point.plotY - 10
};
},
style: {
fontSize: "10px",
fontWeight: "unbold"
},
formatter: function() {
return Math.round(chartData[index - 2] * 100) / 100;
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
},
series: {
borderColor: '#FFFFFF',
animation: false, //disable all the animations,
pointPadding: 0,
groupPadding: 0,
borderWidth: 1,
shadow: false
}
},
series: [{
enableMouseTracking: false,
data: Array(7).fill(0)
}]
});
return chart;
}
So, it's only possible to reproduce on Windows platform. Could you provide us also with minified demo where the problem occurs? I'm asking because in current demo there are a lot of lines which are unnecessary.
Additionally, until we find the source of the problem, you can workaround it by calling this.reflow() in chart.events.load event handler.
chart: {
events: {
load: function() {
this.reflow()
}
}
}
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#reflow
I'm not sure why but it works fine when you remove the marginLeft property or set it to 0.

dynamic chart with Highcharts using json

I've a question about how to create a dynamic chart using json, I tried and my graph didn't show a result, when I checked out, I've no error with my code. This is my code :
<script>
var chart; // global
function requestData() {
$.ajax({
url: 'api_heartrate.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>`
this is my json :
http://health.barrukurniawan.tech/api_heartrate.php
[{"time":"2018-08-02 09:30:11","nilai_sensor":"78"}]
I tried following a tutorial from this link :
Highcharts Dynamic Chart with MySQL Data doesn't reload
Thanks for your attention, gladly waiting for an answer :)
There are multiple small errors in your approach
eval is bad, parse it using JSON.parse instead.
During load, chart is not defined yet, so your callback will not work.
Highcharts needs time in milliseconds since 1970.
highcharts expects an object {x: , y: ,...} you give it {time: , nilai_sensor: }.
Solutions:
point = JSON.parse(point)
events: {
load: function() {
setInterval(function() {
requestData(chart)
}, 1000);
}
}
new Date(point[0].time).getTime()
{x: new Date(point[0].time).getTime(), y: point[0].nilai_sensor}
Here is a working example using your input with static data(and some added time to keep it moving): https://jsfiddle.net/ewolden/md975oLk/23/

Highcharts Map not rendering no errors

I am attempting to take the example produced by Highcharts here http://www.highcharts.com/maps/demo/color-axis and substitute the data loaded by the $.getJson with a local JSON file called 'testdata1.json'.
The code I've modified below produces no errors yet the map does not render. I think it's because the testdata1.json is loaded late, after the javascript is executed. If so, is there a better way I should be doing this -- perhaps waiting for the data to load before executing the JS file? I attempted to do this by placing a
$(document).ready(
in front of the function but it didn't work. Any thoughts are greatly appreciated, I think it's something relatively minor that is just escaping me.
Thank you.
$(function () {
// Map options
var options = {
chart : {
renderTo: '#map',
borderWidth : 1
},
title : {
text : 'US population density (/km²)'
},
legend: {
layout: 'horizontal',
borderWidth: 0,
backgroundColor: 'rgba(255,255,255,0.85)',
floating: true,
verticalAlign: 'top',
y: 25
},
mapNavigation: {
enabled: true
},
colorAxis: {
min: 1,
type: 'logarithmic',
minColor: '#EEEEFF',
maxColor: '#000022',
stops: [
[0, '#EFEFFF'],
[0.67, '#4444FF'],
[1, '#000022']
]
},
series : [{
animation: {
duration: 1000
},
mapData: Highcharts.maps['countries/us/us-all'],
joinBy: ['postal-code', 'code'],
dataLabels: {
enabled: true,
color: 'white',
format: '{point.code}'
},
name: 'Population density',
tooltip: {
pointFormat: '{point.code}: {point.value}/km²'
}
}]
};
$.getJSON('static/data/testdata1.json', function (data) {
// Make codes uppercase to match the map data
$.each(data, function () {
this.code = this.code.toUpperCase();
});
options.series.data= data;
var chart = new Highcharts.Chart(options)
});
});
You have three problems. Here's a fiddle based on their sample that uses your approach, but still uses their data, and works: http://jsfiddle.net/g29k24vw/1/
Here are the important parts:
chart : {
renderTo: 'container',
borderWidth : 1,
type: 'map'
},
And:
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=us-population-density.json&callback=?', function (data) {
// Make codes uppercase to match the map data
$.each(data, function () {
this.code = this.code.toUpperCase();
});
options.series[0].data= data;
var chart = new Highcharts.Chart(options);
});
Note the differences here:
You need to specify the chart type in options if you're going to instantiate the chart object directly instead of using the jQuery helper.
renderTo doesn't want a hash in front of the element name.
options.series[0].data, not options.series.data...series is actually an array of objects.

Data Not Showing in Highcharts

I'm attempting to combine a couple of different chart demos from Highcharts.
My examples are: Data classes and popup and Small US with data labels
I want the map from the first with the popup feature of the second. I need to connect the map to my own google spreadsheet but for now I'm just trying to get the data from the first example to work.
This is what I have so far but can't seem to get any data in the map. I thought I had a joinBy problem, and I may still, but when I set joinBy to null I thought "the map items are joined by their position in the array", yet nothing happened.
https://jsfiddle.net/9eq6mydv/
$(function () {
// Load the data from a Google Spreadsheet
// https://docs.google.com/a/highsoft.com/spreadsheet/pub?hl=en_GB&hl=en_GB&key=0AoIaUO7wH1HwdFJHaFI4eUJDYlVna3k5TlpuXzZubHc&output=html
Highcharts.data({
googleSpreadsheetKey: '0AoIaUO7wH1HwdDFXSlpjN2J4aGg5MkVHWVhsYmtyVWc',
googleSpreadsheetWorksheet: 1,
// custom handler for columns
parsed: function (columns) {
// Make the columns easier to read
var keys = columns[0],
names = columns[1],
percent = columns[10],
// Initiate the chart
options = {
chart : {
renderTo: 'container',
type: 'map',
borderWidth : 1
},
title : {
text : 'US presidential election 2008 result'
},
subtitle: {
text: 'Source: <a href="http://en.wikipedia.org/wiki/United_States_presidential_election,' +
'_2008#Election_results">Wikipedia</a>'
},
mapNavigation: {
enabled: true,
enableButtons: false
},
legend: {
align: 'right',
verticalAlign: 'top',
x: -100,
y: 70,
floating: true,
layout: 'vertical',
valueDecimals: 0,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || 'rgba(255, 255, 255, 0.85)'
},
colorAxis: {
dataClasses: [{
from: -100,
to: 0,
color: '#C40401',
name: 'McCain'
}, {
from: 0,
to: 100,
color: '#0200D0',
name: 'Obama'
}]
},
series : [{
data : data,
dataLabels: {
enabled: true,
color: '#FFFFFF',
format: '{point.code}',
style: {
textTransform: 'uppercase'
}
},
mapData: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']),
joinBy: keys,
name: 'Democrats margin',
point: {
events: {
click: pointClick
}
},
tooltip: {
ySuffix: ' %'
},
cursor: 'pointer'
}, {
type: 'mapline',
data: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small'], 'mapline'),
color: 'silver'
}]
};
/**
* Event handler for clicking points. Use jQuery UI to pop up
* a pie chart showing the details for each state.
*/
function pointClick() {
var row = this.options.row,
$div = $('<div></div>')
.dialog({
title: this.name,
width: 400,
height: 300
});
window.chart = new Highcharts.Chart({
chart: {
renderTo: $div[0],
type: 'pie',
width: 370,
height: 240
},
title: {
text: null
},
series: [{
name: 'Votes',
data: [{
name: 'Obama',
color: '#0200D0',
y: parseInt(columns[3][row], 10)
}, {
name: 'McCain',
color: '#C40401',
y: parseInt(columns[4][row], 10)
}],
dataLabels: {
format: '<b>{point.name}</b> {point.percentage:.1f}%'
}
}]
});
}
// Read the columns into the data array
var data = [];
$.each(keys, function (i, key) {
data.push({
key: key,//.toUpperCase(),
value: parseFloat(percent[i]),
name: names,
row: i
});
});
// Initiate the chart
window.chart = new Highcharts.Map(options);
},
error: function () {
$('#container').html('<div class="loading">' +
'<i class="icon-frown icon-large"></i> ' +
'Error loading data from Google Spreadsheets' +
'</div>');
}
});
});
UPDATE:
I wanted to share with everyone my final solution. Although Ondkloss did a magnificent job answering my question the popup feature still didn't work and this is because I forgot to include the jQuery for the .dialog call. Once I included that I had an empty popup with a highchart error 17, this is because the highmaps.js code doesn't include the pie chart class. So I had to add the highcharts.js code and include map.js module afterward. You can see my final jsfiddle here.
Thanks again to Ondkloss for the excellent answer!
The problem here mostly comes down to the use of joinBy. Also to correct it there are some required changes to your data and mapData.
Currently your joinBy is an array of strings, like ["al", "ak", ...]. This is quite simply not an accepted format of the joinBy option. You can read up on the details in the API documentation, but the simplest approach is to have a attribute in common in data and mapData and then supply a string in joinBy which then joins those two arrays by that attribute. For example:
series : [{
data : data,
mapData: mapData,
joinBy: "hc-key",
]
Here the "hc-key" attribute must exist in both data and mapData.
Here's how I'd create the data variable in your code:
var data = [];
$.each(keys, function (i, key) {
if(i != 0)
data.push({
"hc-key": "us-"+key,
code: key.toUpperCase(),
value: parseFloat(percent[i]),
name: names[i],
row: i
});
});
This skips the first key, which is just "Key" (the title of the column). Here we make the "hc-key" fit the format of the "hc-key" in our map data. An example would be "us-al". The rest is just metadata that will be joined in. Note that you were referencing your data in the options prior to filling it with data, so this has to be moved prior to this.
This is how I'd create the mapData variable in your code:
var mapData = Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']);
// Process mapdata
$.each(mapData, function () {
var path = this.path,
copy = { path: path };
// This point has a square legend to the right
if (path[1] === 9727) {
// Identify the box
Highcharts.seriesTypes.map.prototype.getBox.call(0, [copy]);
// Place the center of the data label in the center of the point legend box
this.middleX = ((path[1] + path[4]) / 2 - copy._minX) / (copy._maxX - copy._minX);
this.middleY = ((path[2] + path[7]) / 2 - copy._minY) / (copy._maxY - copy._minY);
}
// Tag it for joining
this.ucName = this.name.toUpperCase();
});
The first part is your "standard map data". The rest is to correctly center the labels for the popout states, and gotten directly from the example.
And voila, see this JSFiddle demonstration to witness your map in action.
I suggest doing some console.log-ing to see how data and mapData have the hc-key in common and that leads to the joining of the data in the series.

HighCharts, multiple charts on page call via function

Hopefully someone can help me as I'm stuck at the moment after searching for a solution already for the last 2 days.
I decided to look into HighCharts yesterday for a new project and it does do what I'm after. However I'm trying to make the implementation option into my WordPress plugin as clean as possible and that's where I'm stuck at the moment.
This JSFiddle is working and shows what I like to get as output: http://jsfiddle.net/golabs/tpKU3/
But I would like to be able to create a new chart by just calling a function and supply the target div ID and the 2 dataArray's. My attempt can be found here: http://jsfiddle.net/golabs/rstpA/
or see the jscode here:
/**
* However this second section of code does NOT work as nothing is displayed in the container21 div...
* What am I doing wrong here?
* I like to be able to create a new chart by only supplying the target div ID and the dataArray's, this
* to have be able to manage the general settings centrally.
*
* This JSFIDDLE is related to: http://jsfiddle.net/golabs/tpKU3/
**/
$(function () {
var __catergories__ = ['AAA','BBB','CCC','DDD','EEE','FFF','GGG'];
var getChartConfig = function( renderId, dataArray1, dataArray2 ) {
var config = {};
config.chart = {
renderTo: renderId, polar: true, type: 'line', height: 254, width: 360, className: 'SpiderPolarChart', backgroundColor: 'rgba(101,101,101,.1)'
};
config.title = {
text: ''
};
config.legend = {
layout: 'horizontal', align: 'center', verticalAlign: 'bottom', y: -3,
};
config.credits = {
enabled: true, text: 'highcharts.com', href: 'http://highcharts.com/', position: {
verticalAlign: 'bottom',
x: -11,
}
};
config.pane = {
startAngle: -90, endAngle: 90, center: ['50%', '93%'], size: 300, background: null
};
config.xAxis = {
categories: __catergories__,
tickmarkPlacement: 'on', tickPixelInterval: 1, lineWidth: 0, labels: {
rotation: 'auto',
distance: 12
}, showLastLabel: true
};
config.yAxis = {
gridLineInterpolation: 'circle', gridLineDashStyle: 'LongDash', tickInterval: 1, lineWidth: 0, min: 0, max: 5, ceiling: 5, labels: {
x: 4, y: 15
}, showLastLabel: true
};
config.exporting = {
enabled: false
};
config.tooltip = {
shared: true, pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}</b><br/>'
};
config.series = [{
name: 'Overall Rating', data: dataArray1, color: '#D4A539', type: 'area', pointPlacement: 'on', connectEnds: false, index: 1, legendIndex: 2
},{
name: 'Personal Rating', data: dataArray2, color: '#333', type: 'line', pointPlacement: 'on', connectEnds: false, index: 2, legendIndex: 1
}];
return config;
};
// ===========================================================================
charts.push(new Highcharts.Chart(
getChartConfig( "container21", [1.5,3,2,3,4,1,2], [1,4,1.5,3,2,3,1] )
));
});
I've run the code through JSHint.com so all typos should be tackled as it doesn't show any errors at the moment.
I hope someone can guide me into the right direction to get this to work.
Cheers!
** Updated the links to the JSFiddles **
** ISSUE RESOLVED, see below **
In this jsFiddle (http://jsfiddle.net/golabs/rstpA/) you are not telling it what chart is. You are trying to set the options for a chart that you have not created to update the options you are passing. It is sort of backwards.
Here is a quick "fix":
var newChart = new Highcharts.Chart(
getChartConfig( "container21", [1.5,3,2,3,4,1,2], [1,4,1.5,3,2,3,1] )
);
Now, I would think it would be better to setup a global option set and then merge in your new set (specific to chart you want to build) as in my linked SO answer. This may or may not give you more flexibility.
charts was not defined.
Is this the solution you are looking for?
var charts = [];
charts.push(new Highcharts.Chart(
getChartConfig( "container21", [1.5,3,2,3,4,1,2], [1,4,1.5,3,2,3,1] )
));
http://jsfiddle.net/37Gsv/1/
you may try this:
var charts = [];
var i=0;
for (i =1; i< 10; i++){
var o =i.toString();
charts.push(new Highcharts.Chart(
getChartConfig( "container2"+o, [1.5,3,2,3,4,1,2], [1,4,1.5,3,2,3,1] )
));
}
test link: http://jsfiddle.net/newpiseth/8u0tkkkL/5/

Categories