Full Graphic(javascript flot plugin) to image(png) - javascript

i'm using the flot plugin for javascript to plot some graphics on a web software, it works perfectly..I can plot the graphic, export the data to an .xls file, save the graphic figure as a .png file(both you can choose the name of the file)
Anyway, it plot something like the image below..
How the plot shows in the web-site
but when I click the button to save it to .png, the image is the below..How the plot shows in the downloaded file
I need that the downloaded file includes the axis numbers(in the exemple 0,10,...,100 and the y-axis too)
how to?
the importants part of the code are below(... is for code that is not needed here):
function gerar_graficos(varArray, eixo_x, eixo_y) {
...
$.ajax({
type: "POST",
url: '{% url "micro:micro_graficos_calc" %}', // micro.views.micro_graficos_calc
data: JSON.stringify({
fibra:fibra, matriz:matriz, fibra_nome:fibra_nome, matriz_nome:matriz_nome,
abordagem:abordagem, varArray:varArray, eixo_x:eixo_x, eixo_y:eixo_y, vf:vf, sigma2:sig2
}),
success: function(response) {
var pan_buttons = $("#pan_buttons");
var zoom_buttons = $("#zoom_buttons");
var placeholder = $("#placeholder_grafico");
var data = response.curvas;
var nome_eixo_x = $('#id_select_eixo_x').select2('data').text;
var nome_eixo_y = $('#id_select_eixo_y').select2('data').text;
...
}
$("#flot-tooltip").hide();
...
var tick;
if($('#id_select_eixo_x').val() == 'angulo')
tick = [0, 30, 60, 90, 120, 150, 180]
else
tick = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
var plot = $.plot(placeholder, data, {
xaxis: {
//axisLabel: $('#id_select_eixo_x').select2('data').text,
axisLabel: nome_eixo_x,
axisLabelUseCanvas: true,
axisLabelPadding: 5,
min: response.min_x,
max: response.max_x,
panRange: [response.min_x, response.max_x],
ticks: tick,
},
yaxis: {
//axisLabel: $('#id_select_eixo_y').select2('data').text,
axisLabel: nome_eixo_y,
axisLabelUseCanvas: true,
axisLabelPadding: 5,
tickFormatter: tickFormatter_y,
min: response.min_y,
max: response.max_y,
panRange: [response.min_y, response.max_y],
},
series: {
lines: {
show: true
},
shadowSize: 0
},
grid: {
clickable: true,
},
legend: {
show: false,
//container: $('#legenda_grafico')
},
zoom: {
interactive: true,
},
pan: {
interactive: true
}
});
...
$('#salvarImagemGrafico').show();
$("#ImagemGrafico").on("click", function(){
var myCanvas = plot.getCanvas();
dialogNomeImagem(myCanvas);
});
...
function dialogNomeImagem(myCanvas){
bootbox.dialog( 'Digite o nome do arquivo(não necessário colocar .png no final): <br>\
<form><input class = "input-block-level" id = "dialogIMG" type = "text"/>Padrão: imagem.png</form>',
[
{
"label": "OK",
"class": "btn-primary primary",
"callback": function(){
var MIME_TYPE = "image/png";
var imgURL = myCanvas.toDataURL(MIME_TYPE);
var dlLink = document.createElement('a');
var nome;
if(!$("#dialogIMG").val())
nome = 'imagem';
else
nome = $("#dialogIMG").val();
dlLink.download = nome;
dlLink.href = imgURL;
dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
document.body.appendChild(dlLink);
dlLink.click();
document.body.removeChild(dlLink);
}
},
{
"label": "Cancelar",
"class": "btn-primary",
}
],
{
"header": "",
"onEspace": true,
} );
}
HTML:
<div id="divResultados">
<div id='buttons_grafico'>
<span id='pan_buttons'>
</span>
<span id='zoom_buttons'>
</span>
<span id='flot-tooltip'>
</span>
</div>
<div id='placeholder_grafico'></div>
<div id='legenda_grafico'></div>
...
<div id='salvarImagemGrafico'>
<input type="submit" id="ImagemGrafico" class="btn btn-primary" value="Salvar Imagem">
</div>
...
</div>
big post..I know, I'm sorry, but really hope that you guys can help me..
and yes, I've looked for other topics here and found some, but my problem is that I need to keep changing the name of the file and none of the codes worked for that..

Using the jquery.flot.canvas.js plugin you need canvas: true in your options. See this example and its source on the Flot page.

Related

Highcharts Local CSV Issues

I am having issues creating my Highcharts graph out of my csv data. I have the following code that seems that it should work but it produces a blank graph on my server, I think it has something to do with the way that I'm pulling my data. I am using a ajax requests to pull from the csv file and plot the points. My csv is formatted like this.
0,0,0,12:45:37
5,26,130,12:45:37
1,28,28,12:45:42
4,35,140,12:45:47
1,32,32,12:45:52
3,16,48,12:45:57
1,29,29,12:46:02
1,25,25,12:46:07
5,16,80,12:46:12
4,35,140,12:46:17
5,25,125,12:46:22
4,37,148,12:46:27
With new points being added to the csv file every 30 seconds.
This is my code producing a blank graph.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Load cells data</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var t = [];
var Cell1 = [];
var Cell2 = [];
var Cell3 = [];
$.get('test.csv',function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var date = items[0].split('/');
Cell1.push([date, parseFloat(items[1])]);
Cell2.push([date, parseFloat(items[2])]);
Cell3.push([date, parseFloat(items[0])]);
});
var options = {
chart: {
zoomType: 'x',
renderTo: 'chart',
defaultSeriesType: 'line',
animation: Highcharts.svg,
events: {
load: requestData
}
},
title: {
text: 'Reading chart'
},
xAxis: {
title: {
text: 'Date'
},
type: 'datetime'
},
yAxis: {
title: {
text: 'kN'
}
},
series: [{
data: Cell1},{data: Cell2
}, {data: Cell3}],
//barra vertical que une puntos
tooltip: {
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1,
x3: 0,
y3: 2
},
stops: [
[0, 'rgba(96, 96, 96, .8)'],
[1, 'rgba(16, 16, 16, .8)'],
[2, 'rgba(50, 50, 50, .8)']
]
},
borderWidth: 0,
style: {
color: '#FFF'
},
crosshairs: true,
shared: true
},
// quitar link Highcharts
credits: {
position: {
align: 'left',
verticalAlign: 'bottom',
x: 0,
y: -10
},
style: {
cursor: 'pointer',
fontSize: '20px',
color: 'rgba(0, 0, 0, 0)'
},
text: 'R E M t i m er.com',
href: 'http://Google.com'
},
// finn quitar link highcharts
};
var chart = new Highcharts.StockChart(options);
function requestData() {
$.ajax({
csv: '\\server\\test.csv',
success: function(csv) {
var items = csv.split(',');
var date = items[0].split('/');
Cell1 = parseFloat(items[1]),
Cell2 = parseFloat(items[2]),
Cell3 = parseFloat(items[3]),
point = [date, Cell1];
point2 = [date, Cell2];
point3 = [date, Cell3];
chart.series[0].addPoint(point);
chart.series[1].addPoint(point2)
chart.series[2].addPoint(point3)
// call it again after one second
setTimeout(requestData, 30000);
},
cache: false
});
}
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="chart" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Please help.
You need to put date as timestamp.
Since the csv date doesn't contain the day, I suggest put the current date (but check your requirements).
Try this (create a new date based on string in ISO 8601 format):
var date = new Date(new Date().toISOString().substr(0,10) + 'T' + items[3])

Custom Map in Datamaps

Hello I'm using d3 js with datamaps and I want to show the few countries of the world. I have checked the online forum for the help but not get cleared idea or response.
Source code :
<div id="container" style="position: relative; width: 900px; height: 500px;"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="http://datamaps.github.io/scripts/0.4.4/datamaps.world.min.js"></script>
<script>
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(0,0,0)',
defaultFill: 'green'
},
dataType: 'json', //for use with dataUrl, currently 'json' or 'csv'. CSV should have an `id` column
dataUrl: null,
geographyConfig: {
dataUrl: null, //if not null, datamaps will fetch the map JSON (currently only supports topojson)
hideAntarctica: true,
borderWidth: 1,
borderOpacity: 1,
borderColor: '#FDFDFD',
popupTemplate: function(geography, data) { //this function should just return a string
return '<div class="hoverinfo"><strong>' + geography.properties.name + '</strong></div>';
},
popupOnHover: true, //disable the popup while hovering
highlightOnHover: true,
highlightFillColor: '#FC8D59',
highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
highlightBorderWidth: 2,
highlightBorderOpacity: 1
},
done: function(datamap) {
datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
console.log(geography);
var url = window.location.href;
var arr = url.split("/");
var result = arr[0] + "//" + arr[2]
window.open(result+'/countries/view/'+geography.properties.name);
});
}
});
</script>
It'll display all the countries. but i want to show few country.
How can I pass the country list over there?
I think with the help of custom.json or topojson. I don't know. Let me know if you have any solution or guidance.

Highcharts load before the dialog has opened

I have a dynamic highchart that is shown in a dialog on a click event. I am close to where I want to be on this, with the exception of the following:
1: My chart has an event: load included, which means the chart is loaded before the click event. I want it to load on the click event. My first instinct was to place the highchart code in the onclick event, but that had unexpected impacts on the chart rendering itself. How can I have the chart load on the click event without impacting the chart behavior?
2: The left hand side of my chart does not disappear from the chart, as shown in the jsfiddle example from the highcharts website: http://jsfiddle.net/gh/get/jquery/3.1.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/dynamic-update/ and I do not see any difference between the example and my code that would impact this. How can I have my chart copy the example and have my points disappear on the left?
3: When my chart has reached the end of the data array, I want it to start over, but instead it seems to keep running without data, eventually flatlining. My dataset includes 3 arrays, each of 40 elements; apiData, calculatedData (both numbers), and apiDate (universal time values). How can I have the chart run a continuous loop on my data?
Example of my data:
var apiData = [75, 76, 89, 91, 86, 56, 46, 89, 87, 96];
var calculatedData = [78, 81, 98, 95, 89, 70, 59, 91, 90, 78];
var apiDate = [1482613200,1482624000,1482634800,1482645600,1482656400
,1482667200,1482678000,1482688800,1482699600,1482710400,1482721200];
These divs have the onClick event attached:
<div class="wrap">
<div class="left col-xs-4"
id="8d450007-9cbf-11e6-a7da-14109fd4bd8b">
</div>
<div class="center col-xs-4"
id="8d45001c-9cbf-11e6-a7da-14109fd4bd8b">
</div>
<div class="right col-xs-4"
id="8d450008-9cbf-11e6-a7da-14109fd4bd8b">
</div>
</div>
Dialog that contains the chart:
<!-- Div to hold the line chart -->
<div id="dialog" title="Basic dialog">
<div id="canvas" width="600" height="400"></div>
</div>
Dialog setup:
//Initialize the dialog and set options
var opt = {
autoOpen: false,
modal: true,
width: 660,
height:460,
title: 'Hourly Temperature'
};
var theDialog = $("#dialog").dialog(opt);
var divIdList = ["#8d45001c-9cbf-11e6-a7da-14109fd4bd8b", "#8d450007-9cbf-11e6-a7da-14109fd4bd8b", "#8d450008-9cbf-11e6-a7da-14109fd4bd8b"]
$(function () {
divIdList.forEach(function(id) {
$(id).click(function () {
theDialog.dialog('open');
});
})
});
Highchart code:
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
Highcharts.chart('canvas', {
chart: {
type: 'spline',
animation: Highcharts.svg,
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each 3 seconds
var series1 = this.series[0];
var series2 = this.series[1];
var seriesCount = 0;
setInterval(function () {
var x = (new Date(apiDate[seriesCount] * 1000)).getTime(),
y1 = apiData[seriesCount],
y2 = calculatedData[seriesCount];
series1.addPoint([x, y1], true, true);
series2.addPoint([x, y2], true, true);
seriesCount++;
}, 3000);
if (seriesCount > 10) {
char
}
}
}
},
title: {
text: 'Live data'
},
xAxis: {
title: {
text: 'Date/Time'
},
type: 'datetime',
tickPixelInterval: 150
},
yAxis: [{
title: {
text: 'Temperature'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}
],
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 0);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'API Temperature data',
data: (function () {
// use api predicted data
var data = [],
time = (new Date(apiDate[0])).getTime(),
dataCount = 0,
i;
for (i = 0; i <= 40; i ++) {
data.push({
x: time,
y: apiData[dataCount]
});
}
return data;
}())
},
{
name: 'Calculated Temperature data',
data: (function () {
var data = [],
time = (new Date(apiDate[0])).getTime(),
dataCount = 0,
i;
for (i = 0; i <= 40; i ++) {
data.push({
x: time,
y: calculatedData[dataCount]
});
}
return data;
}())
}
]
});
});
I would really appreciate some help on this. Maybe it is really simple but I have been staring at it so long now, I'm driving myself crazy.

Highcharts reloading issue with Backbone.js

I'm struggling to solve a problem I have with getting a chart to be redrawn after navigating to another view and then return back to the same chart view.
I'm using Backbone.js and Underscore as a MVC and templating solution for my application.
When I navigate to the charting page initially it works great, but if I move away and then come back I get a `TypeError: chart.series[0] is undefined in the console log.
I have highlighted line where the error occurs in the code below, close to the end.
My thought is that I may need to destroy() the chart at some point, but I'm unsure where I would do this and if it would solve my problem.
I recently changed the script to now use HighStock 'Highstock JS v1.3.6 (2013-10-04)' from earlier HighCharts ver 2.3.5, where it appeared that I did not have this issue.
The app is live online if anyone really needs or wants to see it in action, let me know.
The following code section is the function thatis called by the Backbone router.
If there is a need for other sections of code, please let me know.
I'll be grateful for any advice.
EDIT:
I have managed to get this in JSFiddle for anyone to view the problem.
Clickty clack your fury tailless one here http://jsfiddle.net/rockwallaby/pqKWj
When you first run it up, you will get a trend being displayed.
Then hit the 'Go to a different page' link, you will get a fairly blank page.
On that page there is a link to bring you back to the trend page.
Hitting that link brings you back but the trend does not get rendered correctly due to the above mentioned error.
//=================================================================================
// trendsBattery
// A simple trend view showing Battery Volts and Solar Charge
//
window.trendsBattery = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendsTemplate),
chart: null,
chartoptions:{
chart: {
renderTo: 'chart-container',
},
rangeSelector: {
enabled: false,
},
title:{
text:'Battery Volts & Solar Amps'
},
xAxis: {
type:'datetime',
dateTimeLabelFormats: {month:'%e. %b',year:'%b'}
},
yAxis: [{
title :{text: 'Battery Volts'},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0',
},
{
title :{text: 'Solar Charge Amps'},
min: 0,
max: 16,
opposite: true,
},
],
series:[
{yAxis: 0, data: [], type: 'line', step: true, name: 'Battery Vdc'},
{yAxis: 1, data: [], type: 'line', step: true, name: 'Solar Amps'},
],
},
render:function() {
that = this;
$(this.el).html(this.template());
this.chartoptions.chart.width = (windowWidth);
this.chartoptions.chart.height = (windowHeight - 150);
setTimeout(function() {
chart = new Highcharts.StockChart(that.chartoptions);
chart.events ={load: that.requestData(this.chart) };
},20);
return this;
},
requestData: function(chart){
var querystring = '//myHostServer.com/myFolder/myPHP.php';
jQuery.get(querystring, null, function(csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
};
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0]) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
};
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
},
});
I just updated jsfiddle with the suggestion I provided in comment, it's working.
window.trendView = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendTemplate),
chart: null,
getChartOptions: function () {
return {
chart: {
animation: true,
renderTo: 'chart-container',
backgroundColor: '#fff'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Battery Volts & Solar Amps'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
} // don't display the dummy year:
},
yAxis: [{
title: {
text: 'Battery Volts'
},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0'
}, {
title: {
text: 'Solar Charge Amps'
},
min: 0,
max: 16,
opposite: true
}],
series: [{
yAxis: 0,
data: [],
type: 'line',
step: true,
name: 'Battery Vdc'
}, {
yAxis: 1,
data: [],
type: 'line',
step: true,
name: 'Solar Amps'
}]
}
},
render: function () {
that = this;
$(this.el).html(this.template());
var chartOptions = that.getChartOptions();
chartOptions.chart.width = (windowWidth - 50);
chartOptions.chart.height = (windowHeight - 50);
setTimeout(function () {
chart = new Highcharts.StockChart(chartOptions);
chart.events = {
load: that.requestData(this.chart)
};
}, 20);
return this;
},
requestData: function (chart) {
var querystring = '//paulalting.com/hydrosolar/clientGET.php?id=trendVolts&start=6400&size=200';
console.log(querystring);
jQuery.get(querystring, null, function (csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0], 10) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
}
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
}
});
here is the link
http://jsfiddle.net/pqKWj/14/
If you are interested let me know I see some more similar problems in the code, which I think fine for now, but will create issues, when you have 2 charts in the same page etc. we can talk

Plotting json on .JS

I am trying to plot some json data but for some reason code is not workingLet me show my code.
My json looks like this:
{"d1":[[1356912000000, 1],[1356825600000, 1],[1356739200000, 1],[1356652800000, 1],[1356566400000, 38],[1356480000000, 47],[1356393600000, 1],[1356307200000, 4],[1356220800000, 1],[1356134400000, 2],[1356048000000, 50],[1355961600000, 51],[1327017600000, 38],[1326931200000, 52],[1326844800000, 45],[1326758400000, 49],[1326672000000, 46],[1326585600000, 1],[1326499200000, 5],[1326412800000, 44],[1326326400000, 48],[1326240000000, 43],[1326153600000, 46],[1326067200000, 41],[1325980800000, 1],[1325894400000, 4],[1325808000000, 45],[1325721600000, 43],[1325635200000, 42],[1325548800000, 42],[1325462400000, 43]]}
I am trying to plot with following code:
$(document).ready(function () {dashboard_A_chart.chartVisit ();});
dashboard_A_chart = {
chartVisit: function () {
var elem = $('#dashChartVisitors');
var options = {
colors: ["#edc240", "#5EB95E"],
legend: {
show: true,
noColumns: 2,
labelFormatter: null,
labelBoxBorderColor: false,
container: null,
margin: 8,
backgroundColor: false
},
xaxis: {
mode: "time",
font: {
weight: "bold"
},
color: "#D6D8DB",
tickColor: "rgba(237,194,64,0.25)",
min: "1325462400000",
max: "1356912000000",
tickLength: 5
},
selection: {
mode: "x"
},
};
var d1 = []
function onDataReceived(series) {d1 = [ series ];$.plot(elem, d1, options);}
$.ajax({
url: "../giga/data/dados1.json",
method: 'GET',
dataType: 'json',
success: onDataReceived
});
},
};
you are trying to call dashboard_A_chart.chartVisit() which is a function of an object literal which needs to be defined before.
you are creating the elem and options var inside the inside the chartVisit-function, but trying to use it in your onDataReceived-Function where it is not present.
it pretty much looks like you just copy & pasted some stuff together. take a looke at this code, that should work:
$(document).ready(function () {
var elem = $('#dashChartVisitors');
var options = {
colors: ["#edc240", "#5EB95E"],
legend: {
show: true,
noColumns: 2,
labelFormatter: null,
labelBoxBorderColor: false,
container: null,
margin: 8,
backgroundColor: false
},
xaxis: {
mode: "time",
font: {
weight: "bold"
},
color: "#D6D8DB",
tickColor: "rgba(237,194,64,0.25)",
min: "1325462400000",
max: "1356912000000",
tickLength: 5
},
selection: {
mode: "x"
}
};
$.ajax({
url: "../giga/data/dados1.json",
method: 'GET',
dataType: 'json',
success: function (data) {
$.plot(elem, data, options);
}
});
});

Categories

Resources