Highcharts maps with decimals - javascript

I try to replicate this example file of highcharts with a different kind of data file. In the new database, life expectancy per country is 13 decimal places. The source is also world bank, which makes the structure comparable. Here is the example JSFIDDLE. Unfortunately, this does not work because presumably "numRegex = /^[0-9.]+$/" on line 26 is wrong. Unfortunately I have no idea what should be put here.
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/maps/modules/map.js"></script>
<script src="https://code.highcharts.com/mapdata/custom/world.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css">
<!-- Flag sprites service provided by Martijn Lafeber, https://github.com/lafeber/world-flags-sprite/blob/master/LICENSE -->
<link rel="stylesheet" type="text/css" href="//github.com/downloads/lafeber/world-flags-sprite/flags32.css" />
<div class="container_fluid">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="panel color-orange shadow">
<div class="panel-heading text-white text-center">
</div>
<div class="panel-body color-grey text-center">
<div class="col-lg-12 col-md-12 position-padding-ver position-padding-hor">
<div id="wrapper_landkaart">
<div id="container"></div>
<div id="info">
<span class="f32"><span id="flag"></span></span>
<h2></h2>
<div class="subheader">Click countries to view history</div>
<div id="country-chart"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScript
$.ajax({
url: 'https://cdn.filestackcontent.com/WZkkd6c4S3euwmgoV88v',
success: function(csv) {
// Parse the CSV Data
/*Highcharts.data({
csv: data,
switchRowsAndColumns: true,
parsed: function () {
console.log(this.columns);
}
});*/
// Very simple and case-specific CSV string splitting
function CSVtoArray(text) {
return text.replace(/^"/, '')
.replace(/",$/, '')
.split('","');
}
csv = csv.split(/\n/);
var countries = {},
mapChart,
countryChart,
numRegex = /^[0-9\.]+$/,
lastCommaRegex = /,\s$/,
quoteRegex = /\"/g,
categories = CSVtoArray(csv[2]).slice(4);
// Parse the CSV into arrays, one array each country
$.each(csv.slice(3), function(j, line) {
var row = CSVtoArray(line),
data = row.slice(4);
$.each(data, function(i, val) {
val = val.replace(quoteRegex, '');
if (numRegex.test(val)) {
val = parseInt(val, 10);
} else if (!val || lastCommaRegex.test(val)) {
val = null;
}
data[i] = val;
});
countries[row[1]] = {
name: row[0],
code3: row[1],
data: data
};
});
// For each country, use the latest value for current population
var data = [];
for (var code3 in countries) {
if (countries.hasOwnProperty(code3)) {
var value = null,
year,
itemData = countries[code3].data,
i = itemData.length;
while (i--) {
if (typeof itemData[i] === 'number') {
value = itemData[i];
year = categories[i];
break;
}
}
data.push({
name: countries[code3].name,
code3: code3,
value: value,
year: year
});
}
}
// Add lower case codes to the data set for inclusion in the tooltip.pointFormat
var mapData = Highcharts.geojson(Highcharts.maps['custom/world']);
$.each(mapData, function() {
this.id = this.properties['hc-key']; // for Chart.get()
this.flag = this.id.replace('UK', 'GB').toLowerCase();
});
// Wrap point.select to get to the total selected points
Highcharts.wrap(Highcharts.Point.prototype, 'select', function(proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
var points = mapChart.getSelectedPoints();
if (points.length) {
if (points.length === 1) {
$('#info #flag').attr('class', 'flag ' + points[0].flag);
$('#info h2').html(points[0].name);
} else {
$('#info #flag').attr('class', 'flag');
$('#info h2').html('Comparing countries');
}
$('#info .subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');
if (!countryChart) {
countryChart = Highcharts.chart('country-chart', {
chart: {
height: 250,
spacingLeft: 0
},
credits: {
enabled: false
},
title: {
text: null
},
subtitle: {
text: null
},
xAxis: {
tickPixelInterval: 50,
crosshair: true
},
yAxis: {
title: null,
opposite: true
},
tooltip: {
split: true
},
plotOptions: {
area: {
color: '#fa7921'
},
series: {
animation: {
duration: 500
},
marker: {
enabled: false
},
threshold: 0,
pointStart: parseInt(categories[0], 10)
}
}
});
}
$.each(points, function(i) {
// Update
if (countryChart.series[i]) {
/*$.each(countries[this.code3].data, function (pointI, value) {
countryChart.series[i].points[pointI].update(value, false);
});*/
countryChart.series[i].update({
name: this.name,
data: countries[this.code3].data,
type: points.length > 1 ? 'line' : 'area'
}, false);
} else {
countryChart.addSeries({
name: this.name,
data: countries[this.code3].data,
type: points.length > 1 ? 'line' : 'area'
}, false);
}
});
while (countryChart.series.length > points.length) {
countryChart.series[countryChart.series.length - 1].remove(false);
}
countryChart.redraw();
} else {
$('#info #flag').attr('class', '');
$('#info h2').html('');
$('#info .subheader').html('');
if (countryChart) {
countryChart = countryChart.destroy();
}
}
});
// Initiate the map chart
mapChart = Highcharts.mapChart('container', {
title: {
text: 'Population history by country'
},
subtitle: {
text: 'Source: The World Bank'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
type: 'logarithmic',
endOnTick: false,
startOnTick: false,
minColor: '#9E90B3',
maxColor: '#3D1C5C',
min: 50000
},
tooltip: {
footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
},
series: [{
data: data,
mapData: mapData,
joinBy: ['iso-a3', 'code3'],
name: 'Current population',
allowPointSelect: true,
cursor: 'pointer',
states: {
select: {
color: '#D06918',
borderColor: 'black',
dashStyle: 'shortdot'
}
}
}]
});
// Pre-select a country
mapChart.get('us').select();
}
});
Hopefully someone can help me further on this. Thank you very much.

Your CSV file is broken it looks like this:
"Data Source,""World Development Indicators"","
it should look like
"Data Source","World Development Indicators",
CSV won't split on a , if it's in quotes hence you can include comma's in your file as text if you include them in quotes.
Fix your CSV file and it should work.

Related

Adding Context to Django View Causing My Highcharts Map to Disappear

This is my first Django project, and I am working on a Django html template that should contain a Chart.JS bar graph (https://www.chartjs.org/docs/latest/charts/bar.html) alongside a Highcharts drilldown map of the US (https://www.highcharts.com/demo/maps/map-drilldown).
I've successfully implemented my Chart.JS bar graph and passed data to it from our AWS RDS. But now when I try to implement even just the stock Highcharts code from their website, the map fails to render at all. After trying to isolate the problem, I've found that the map does render if I simply delete "context" from the return statement in my view (i.e. delete "context" from the final line in my first block of code below). But this obviously then inhibits my bar graph from rendering. I think I must be missing something with how the highcharts data is loaded in the presence of other context data, but I've been unable to fix it such that both the graph and map render. Any help would be greatly appreciated!
My Django View:
def index(request):
mydb = mysql.connector.connect(
host=xxxx,
user=xxxx,
password=xxxx,
database=xxxx
)
mycursor = mydb.cursor()
mycursor.execute("WITH CS1 AS (SELECT cts.Name, cts.State, m.Frequently, m.Always FROM Masks m JOIN Counties cts ON (m.FIPS = cts.FIPS)) SELECT CS1.State, AVG((CS1.Frequently+CS1.Always)*100) AS Perc_High_Frequency FROM CS1 WHERE CS1.State<>'Puerto Rico' GROUP BY CS1.State ORDER BY Perc_High_Frequency DESC")
tempList = mycursor.fetchall()
statesMaskName = [item[0] for item in tempList]
statesMaskPerc = [item[1] for item in tempList]
context={'statesMaskName':statesMaskName, 'statesMaskPerc':statesMaskPerc}
return render(request,'index.html', context)
The relevant HTML/JS:
<html lang="en" dir="ltr">
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="fixed-header">
<h1>COVID-19 Sentiment and Mask Practices</h1>
</div>
<div>
<div class="col-lg-3" style="float: left; max-height: 6500px;max-width:400px;overflow: scroll; overflow-x:hidden;">
<div style="background-color: #17202A;">
<span style="color: #F7F9F9; text-align: center;"><h4>% Population Who "Frequently" or "Always" Wear Masks When In Public Within 6" of Others (as of July 2-14, 2020)</h4></span>
</div>
<div class="col-lg-12">
<form method="post" enctype="multipart/form-data" action="selectState">
{% csrf_token %}
<div class="col-lg-4" style="float: left; max-height: 3000px;">
<br><br style="line-height: 15px"/>
{% for state in statesMaskName %}
<table style="border-width: 2px; border: #333;">
<tr>
<input type="submit" value="{{state}}" name="statesMaskName" style="width:130px;">
</tr>
</table>
{% endfor%}
</div>
<div style="float: left;">
<canvas id="myChart" height="1360" width="250"></canvas>
</div>
</form>
</div>
</div>
<div class="col-lg-6">
</div>
<div class="col-lg-3">
</div>
</div>
<br>
</body>
<!--my updated code for chartjs graph-->
<script>
const labels = {{statesMaskName|safe}};
const data = {
labels: labels,
datasets: [{
label: '% Population',
color: 'orange',
backgroundColor: 'orange',
borderColor: 'orange',
data: {{statesMaskPerc|safe}},
}]
};
const config = {
type: 'bar',
data,
options: {
indexAxis: 'y',
color: 'white',
scales: {
y: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
},
display: false
},
x: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
// Include a % sign in the ticks
callback: function(value, index, values) {
return value + '%';
}
}
}
}
}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
<!--stock code for highcharts map-->
<div id="usMap" style="height: 500px; min-width: 310px; max-width: 800px; margin: 0 auto"></div>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/data.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="https://code.highcharts.com/maps/modules/offline-exporting.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<script type="text/javascript">
/*
TODO:
- Check data labels after drilling. Label rank? New positions?
*/
let data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']);
const separators = Highcharts.geojson(Highcharts.maps['countries/us/us-all'], 'mapline');
// Set drilldown pointers
data.forEach((d, i) => {
d.drilldown = d.properties['hc-key'];
d.value = i; // Non-random bogus data
});
function getScript(url, cb) {
const script = document.createElement('script');
script.src = url;
script.onload = cb;
document.head.appendChild(script);
}
// Instantiate the map
Highcharts.mapChart('usMap', {
chart: {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
const chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all';
// Handle error, the timeout is cleared on success
let fail = setTimeout(() => {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(() => {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
getScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', () => {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
data.forEach((d, i) => {
d.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: '' });
}
}
},
title: {
text: 'Highcharts Map Drilldown'
},
subtitle: {
text: '',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data: data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}, {
type: 'mapline',
data: separators,
color: 'silver',
enableMouseTracking: false,
animation: {
duration: 500
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
</script>
</html>

Highcharts - Change value of text box when drilling down through chart

Tricky one to explain this so please bear with me.
I have this Large Tree Map created with Highcharts:
http://jsfiddle.net/mb3hu1px/2/
var data = {
"ARS": {
"01To03Years": {
"N": {
"ARGENTINA": 951433
}
},
"Above05Years": {
"N": {
"ARGENTINA": 3719665
}
}
},
"CNY": {
"03To05Years": {
"N": {
"CHINA": 162950484
}
}
},
"COP": {
"Above05Years": {
"N": {
"COLOMBIA": 323390000
}
}
},
"EUR": {
"01To03Years": {
"Y": {
"BELGIUM": 393292575
}
}
}
},
points = [],
currencyPoints,
currencyVal,
currencyI = 0,
periodPoints,
periodI,
yesOrNoPoints,
yesOrNoI,
currency,
period,
yesOrNo,
mil,
causeMil,
causeMilI,
causeName = {
'N': 'Country Name',
'Y': 'Country Name'
};
for (currency in data) {
if (data.hasOwnProperty(currency)) {
currencyVal = 0;
currencyPoints = {
id: 'id_' + currencyI,
name: currency,
color: Highcharts.getOptions().colors[currencyI]
};
periodI = 0;
for (period in data[currency]) {
if (data[currency].hasOwnProperty(period)) {
periodPoints = {
id: currencyPoints.id + '_' + periodI,
name: period,
parent: currencyPoints.id
};
points.push(periodPoints);
yesOrNoI = 0;
for (yesOrNo in data[currency][period]) {
if (data[currency][period].hasOwnProperty(yesOrNo)) {
yesOrNoPoints = {
id: periodPoints.id + '_' + yesOrNoI,
name: yesOrNo,
parent: periodPoints.id,
};
causeMilI = 0;
for (mil in data[currency][period][yesOrNo]) {
if (data[currency][period][yesOrNo].hasOwnProperty(mil)) {
causeMil = {
id: yesOrNoPoints.id + '_' + causeMilI,
name: mil,
parent: yesOrNoPoints.id,
value: Math.round(+data[currency][period][yesOrNo][mil])
};
currencyVal += causeMil.value;
points.push(causeMil);
causeMilI = causeMilI + 1;
}
}
points.push(yesOrNoPoints);
yesOrNoI = yesOrNoI + 1;
}
}
periodI = periodI + 1;
}
}
currencyPoints.value = Math.round(currencyVal / periodI);
points.push(currencyPoints);
currencyI = currencyI + 1;
}
}
Highcharts.chart('container', {
series: [{
type: 'treemap',
layoutAlgorithm: 'squarified',
allowDrillToNode: true,
animationLimit: 1000,
dataLabels: {
enabled: false
},
levelIsConstant: false,
levels: [{
level: 1,
dataLabels: {
enabled: true
},
borderWidth: 3
}],
data: points
}],
title: {
text: ''
}
});
#container {
min-width: 300px;
max-width: 600px;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/heatmap.js"></script>
<script src="https://code.highcharts.com/modules/treemap.js"></script>
<div id="container"></div>
<textarea name="text" id="text" cols="30" rows="10"></textarea>
And as you can see there is also a text area underneath.
What I want is for every level that is clicked through on the chart, the text area updates with some random text.
So for example on the first drill down, the text area could literally just print out level 1, the second drill down print level 2 etc. etc.
If anyone needs anything else from my end please let me know.
Many thanks:)
You can do this several ways. Here is how to do it with plotOptions.series.point.events.click. What you need to do is capture the point click and render some text. As you do not describe what text to show this will just update the textarea with the clicked point's properties name and value.
Highcharts.chart('container', {
series: [{
point: {
events: {
click: function() {
var thePointName = this.name,
thePointValue = this.value;
$('#text').val(function(_, val) {
return 'Category: ' + thePointName + ', value: ' + thePointValue;
});
}
}
},
type: 'treemap',
layoutAlgorithm: 'squarified',
allowDrillToNode: true,
animationLimit: 1000,
dataLabels: {
enabled: false
},
levelIsConstant: false,
levels: [{
level: 1,
dataLabels: {
enabled: true
},
borderWidth: 3
}],
data: points
}],
title: {
text: ''
}
});
Live example.

How to get total of highcharts multiple series

With the Highcharts value-in-legend plugin http://www.highcharts.com/plugin-registry/single/10/Value-In-Legend, I have been able to kind of implement a sort of multiple series total, but I do not understand how to get a total for a clicked y-axis point.
For example when I click, one day I will get the 3 separate series numbers, but I would like to get a total somehow as well, but I only know the y points on load and the visible y-points on redraw. I think the difficulty is getting the total of the 3 series points versus getting the individual point's value.
$(function() {
// Start the standard Highcharts setup
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function(data) {
seriesOptions[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if(seriesCounter == names.length) {
createChart();
}
});
});
// create the chart when all data is loaded
function createChart() {
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function(event) {
console.log('load');
var total = 0;
for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
total += this.series[0].yData[i];
}
totalText_posts = this.renderer.text('Total: ' + total, this.plotLeft, this.plotTop - 35).attr({
zIndex: 5
}).add()
},
redraw: function(chart) {
console.log('redraw');
console.log(totalText_posts);
var total = 0;
for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
if(this.series[0].points[i] && this.series[0].points[i].visible) total += this.series[0].yData[i];
}
totalText_posts.element.innerHTML = 'Total: ' + total;
}
}
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function() {
return(this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
legend: {
enabled: true,
floating: true,
align: 'left',
verticalAlign: 'top',
y: 35,
labelFormat: '<span style="color:{color}">{name}</span>: <b>{point.y:.2f} USD</b> ({point.change:.2f}%)<br/>',
borderWidth: 0
},
plotOptions: {
series: {
compare: 'percent',
cursor: 'pointer',
point: {
events: {
click: function () {
alert('Category: ' + this.category + ', value: ' + this.y);
}
}
}
}
},
series: seriesOptions
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.src.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js"></script>
<div id="container" style="height: 400px; min-width: 500px"></div>
I was able to find out a way to put the total result as a title in a multi series by reading the source code for the Highcharts value-in-legend plugin https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js.
$(function () {
var seriesOptions_likes = [],
seriesCounter_likes = 0,
names_likes = ['MSFT', 'AAPL', 'GOOG'],
totalText_likes = 0;
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createLikesChart() {
Highcharts.stockChart('container_likes', {
chart: {
},
rangeSelector: {
selected: 4
},
title: {
text: 'Total Results: '
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions_likes,
legend: {
enabled: true,
floating: true,
align: 'left',
verticalAlign: 'top',
y: 65,
borderWidth: 0
},
});
}
$.each(names_likes, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
seriesOptions_likes[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter_likes += 1;
if (seriesCounter_likes === names_likes.length) {
createLikesChart();
}
});
});
});
(function (H) {
H.Series.prototype.point = {}; // The active point
H.Chart.prototype.callbacks.push(function (chart) {
$(chart.container).bind('mousemove', function () {
var legendOptions = chart.legend.options,
hoverPoints = chart.hoverPoints,
total = 0;
if (!hoverPoints && chart.hoverPoint) {
hoverPoints = [chart.hoverPoint];
}
if (hoverPoints) {
var total = 0,
ctr = 0;
H.each(hoverPoints, function (point) {
point.series.point = point;
total += point.y;
});
H.each(chart.legend.allItems, function (item) {
item.legendItem.attr({
text: legendOptions.labelFormat ?
H.format(legendOptions.labelFormat, item) :
legendOptions.labelFormatter.call(item)
});
});
chart.legend.render();
chart.title.update({ text: 'Total Results: ' + total.toFixed(2) });
}
});
});
// Hide the tooltip but allow the crosshair
H.Tooltip.prototype.defaultFormatter = function () { return false; };
}(Highcharts));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container_likes" style="height: 400px; min-width: 600px"></div>

FlotChart do not work zooming mode

I have following example: http://jsfiddle.net/ondra15/7mb8K/1/.
I want to have together two example (multiple axes and zooming). Example zooming do not work correct - if I indicate some data in chart for zooming - do not work. Nothing happens.
Original Zooming (correct) solution works here http://www.flotcharts.org/flot/examples/zooming/index.html
Can any some idea for my code? Thanks
code
Hi I managed to get it working using code from an example I found here. I will update your jsfiddle too:
<script type="text/javascript">
var datasets = { ... };
data = null;
function plotByChoice(doAll) {
data = [];
if (doAll != null) {
$.each(datasets, function (key, val) {
data.push(val);
});
}
else {
$('#legend .legendCB').each(
function () {
if (this.checked) {
data.push(datasets[this.id]);
}
else {
data.push({ label: this.id, data: [] })
}
}
);
}
$.plot($("#placeholder"), data, {
yaxes: [{ min: 0 }, { position: "right" }],
xaxis: { tickDecimals: 0 },
legend: {
container: legend,
labelFormatter: function (label, series) {
var cb = '<input class="legendCB" type="checkbox" ';
if (series.data.length > 0) {
cb += 'checked="true" ';
}
cb += 'id="' + label + '" /> ';
cb += label;
return cb;
}
}, selection: { mode: "x" }
});
$('#legend').find("input").click(function () { setTimeout(plotByChoice, 100); });
}
plotByChoice(true);
// Create the overview plot
var overview = $.plot("#overview", data, {
legend: {
show: false
},
series: {
lines: {
show: true,
lineWidth: 1
},
shadowSize: 0
},
xaxis: {
ticks: 4
},
yaxes: [{ min: 0 }, { position: "right" }],
grid: {
color: "#999"
},
selection: {
mode: "x"
}
});
$("#placeholder").bind("plotselected", function (event, ranges) {
var options = {
series: {
lines: { show: true },
points: { show: true }
},
legend: { noColumns: 2 },
xaxis: { tickDecimals: 0 },
yaxis: { min: 0 },
selection: { mode: "x" }
};
var placeholder = $("#placeholder");
placeholder.bind("plotselected", function (event, ranges) {
$("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1));
plot = $.plot(placeholder, data,
$.extend(true, {}, options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
}));
});
// don't fire event on the overview to prevent eternal loop
overview.setSelection(ranges, true);
});
$("#overview").bind("plotselected", function (event, ranges) {
plot.setSelection(ranges);
});
</script>

Not able to find the id in javascript

I'm trying to plot a graph inside a div which is dynamically created. A string of HTML divs is passed from the backend and then it is appended to the comparison_widgets div. Then a call to a function is made which needs to plot a graph(Highcharts) inside that div.
But when it goes to the function it says
Error: Syntax error, unrecognized expression: #id_Asia/Pacific_NorthAmerica
throw new Error( "Syntax error, unrecognized expression: " + msg );
It is not able to find the id, i guess. Where I'm going wrong?
Here result[1] is the div string, ie
<div id="widget_Asia/Pacific_NorthAmerica" class="portlet ui-widget ui-widget-content ui-helper-clearfix ui-corner-all">
<div class="portlet-header ui-corner-all">
<span class="close right">x</span>
Asia / Pacific_North America
</div>
<div id="id_Asia/Pacific_NorthAmerica" class="portlet-content"></div>
</div>
result[2] is id_Asia/Pacific_NorthAmerica
and result[0] is the data that needs to be plotted on the graph.
The AJAX FUNCtion
$.ajax({
dataType : "json",
type: "POST",
url: "/dashboard/",
data : { 'comparison_widget_id' : comparison_widget_id,'level_id':level_id, },
success: function(result){
$("#comparison_widgets").append(result[1]);
var div_id = "id_"+result[2];
comparison_chart(div_id,result[0]);
}
});
function comparison_chart(div_id,result) {
var MAXPOINTS = 20;
var level_number = 0;
Highcharts.setOptions({
global: {
useUTC: false,
}
});
$("#"+div_id).highcharts({
chart: {
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
if(series.data.length > MAXPOINTS){
series.addPoint([x, y], true, true);
}
else{
series.addPoint([x, y], true, false);
}
},5000);
},
}
},
title: {
text: 'Energy Chart'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
tooltip: {
formatter: function() {
var s;
s = this.y + 'kWh';
return s;
}
},
series: [{
type: 'spline',
name: 'Live Data',
data: result[0],
showInLegend: true,
}, {
type: 'pie',
data: result[2],
center: [90, 20],
size: 125,
cursor: 'pointer',
showInLegend: true,
dataLabels: {
enabled: false,
},
point :{
events:{
click : function(){
level_number = level_number + 1;
$.ajax({
dataType: "json",
type : 'POST',
url : '/dashboard/',
data : {'name': this.name, 'level_number' : level_number},
success: function(result){
comparison_chart(result);
}
});
}
}
},
}]
});
}
Use $('#widget_Asia\\/Pacific_NorthAmerica')

Categories