Save graph in a project folder from program in python and pyplot graph in Javascript - javascript

I'm writing in python a program to recognize emotions from voice (it's a web interface and I'm using flask). I passed the variables in JavaScript I created a graph using Plotly. Only now I want to save the graph in a project specific folder called "graphs". How can I do?
I don't want to have to pass the graph from javascript to python and save it. if so how can I do it?
Here's how to build the graph in JavaScript
const x1 = JSON.parse('{{data.audio_len}}');
const y1 = JSON.parse('{{data.val_outputs}}');
console.log(x1);
console.log(y1);
var data = [];
const trace1Values = [];
for (let i = 0; i < x1.length; i++) {
trace1Values.push(y1[i][0]);
}
var Disgusto = {
x: x1,
y: trace1Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Disgusto",
};
data.push(Disgusto);
const trace2Values = [];
for (let i = 0; i < x1.length; i++) {
trace2Values.push(y1[i][1]);
}
var Gioia = {
x: x1,
y: trace2Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Gioia",
};
data.push(Gioia);
const trace3Values = [];
for (let i = 0; i < x1.length; i++) {
trace3Values.push(y1[i][2]);
}
var Paura = {
x: x1,
y: trace3Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Paura",
};
data.push(Paura);
const trace4Values = [];
for (let i = 0; i < x1.length; i++) {
trace4Values.push(y1[i][3]);
}
var Rabbia = {
x: x1,
y: trace4Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Rabbia",
};
data.push(Rabbia);
const trace5Values = [];
for (let i = 0; i < x1.length; i++) {
trace5Values.push(y1[i][4]);
}
var Sorpresa = {
x: x1,
y: trace5Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Sorpresa",
};
data.push(Sorpresa);
const trace6Values = [];
for (let i = 0; i < x1.length; i++) {
trace6Values.push(y1[i][5]);
}
var Tristezza = {
x: x1,
y: trace6Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Tristezza",
};
data.push(Tristezza);
const trace7Values = [];
for (let i = 0; i < x1.length; i++) {
trace7Values.push(y1[i][6]);
}
var Neutrale = {
x: x1,
y: trace7Values,
mode: 'lines+markers',
line: {
shape: 'spline'
},
name: "Neutrale",
};
data.push(Neutrale);
var layout = {
title: '{{data.name_audio}}',
xaxis: {
title: 'Tempo audio in sec'
},
yaxis: {
title: 'Emozioni',
range: [0, 1]
}
};
Plotly.newPlot('myDiv', data, layout);
<div class="grafico" id="myDiv" src='https://cdn.plot.ly/plotly-2.18.0.min.js'></div>
I tried to use this code to save the graph in a folder of my project but when I run the code and show the graph it doesn't save me
Plotly.newPlot('myDiv', data, layout).then(function () {
Plotly.writeImage('myDiv',
{ format: 'png', width: 300, height: 300 },
{ folder: 'grafico/grafico.png' });
});

Related

How do you apply Smart Routing on links with ports on JointJS?

I am trying to apply smart routing of links with the use of ports using JointJS. This documentation shows the one I am trying to achieve. The example on the docs though shows only the programmatic way of adding Link from point A to point B. How do you do this with the use of ports?
Here's my code: JSFiddle.
HTML:
<html>
<body>
<button id="btnAdd">Add Table</button>
<div id="dbLookupCanvas"></div>
</body>
</html>
JS
$(document).ready(function() {
$('#btnAdd').on('click', function() {
AddTable();
});
InitializeCanvas();
// Adding of two sample tables on first load
AddTable(50, 50);
AddTable(250, 50);
});
var graph;
var paper
var selectedElement;
var namespace;
function InitializeCanvas() {
let canvasContainer = $('#dbLookupCanvas').parent();
namespace = joint.shapes;
graph = new joint.dia.Graph({}, {
cellNamespace: namespace
});
paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
}
});
//Dragging navigation on canvas
var dragStartPosition;
paper.on('blank:pointerdown',
function(event, x, y) {
dragStartPosition = {
x: x,
y: y
};
}
);
paper.on('cell:pointerup blank:pointerup', function(cellView, x, y) {
dragStartPosition = null;
});
$("#dbLookupCanvas")
.mousemove(function(event) {
if (dragStartPosition)
paper.translate(
event.offsetX - dragStartPosition.x,
event.offsetY - dragStartPosition.y);
});
// Remove links not connected to anything
paper.model.on('batch:stop', function() {
var links = paper.model.getLinks();
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
if (source.id === undefined || target.id === undefined) {
link.remove();
}
});
});
paper.on('cell:pointerdown', function(elementView) {
resetAll(this);
let isElement = elementView.model.isElement();
if (isElement) {
var currentElement = elementView.model;
currentElement.attr('body/stroke', 'orange');
selectedElement = elementView.model;
} else
selectedElement = null;
});
paper.on('blank:pointerdown', function(elementView) {
resetAll(this);
});
$('#dbLookupCanvas')
.attr('tabindex', 0)
.on('mouseover', function() {
this.focus();
})
.on('keydown', function(e) {
if (e.keyCode == 46)
if (selectedElement) selectedElement.remove();
});
}
function AddTable(xCoord = undefined, yCoord = undefined) {
// This is a sample database data here
let data = [
{columnName: "radomData1"},
{columnName: "radomData2"}
];
if (xCoord == undefined && yCoord == undefined)
{
xCoord = 50;
yCoord = 50;
}
const rect = new joint.shapes.standard.Rectangle({
position: {
x: xCoord,
y: yCoord
},
size: {
width: 150,
height: 200
},
ports: {
groups: {
'a': {},
'b': {}
}
}
});
$.each(data, (i, v) => {
const port = {
group: 'a',
args: {}, // Extra arguments for the port layout function, see `layout.Port` section
label: {
position: {
name: 'right',
args: {
y: 6
} // Extra arguments for the label layout function, see `layout.PortLabel` section
},
markup: [{
tagName: 'text',
selector: 'label'
}]
},
attrs: {
body: {
magnet: true,
width: 16,
height: 16,
x: -8,
y: -4,
stroke: 'red',
fill: 'gray'
},
label: {
text: v.columnName,
fill: 'black'
}
},
markup: [{
tagName: 'rect',
selector: 'body'
}]
};
rect.addPort(port);
});
rect.resize(150, data.length * 40);
graph.addCell(rect);
}
function resetAll(paper) {
paper.drawBackground({
color: 'white'
});
var elements = paper.model.getElements();
for (var i = 0, ii = elements.length; i < ii; i++) {
var currentElement = elements[i];
currentElement.attr('body/stroke', 'black');
}
var links = paper.model.getLinks();
for (var j = 0, jj = links.length; j < jj; j++) {
var currentLink = links[j];
currentLink.attr('line/stroke', 'black');
currentLink.label(0, {
attrs: {
body: {
stroke: 'black'
}
}
});
}
}
Any help would be appreciated. Thanks!
The default link created when you draw a link from a port is joint.dia.Link.
To change this you can use the defaultLink paper option, and configure the router you would like.
defaultLink documentation reference
const paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
},
defaultLink: () => new joint.shapes.standard.Link({
router: { name: 'manhattan' },
connector: { name: 'rounded' },
})
});
You could also provide several default options in the paper.
defaultLink: () => new joint.shapes.standard.Link(),
defaultRouter: { name: 'manhattan' },
defaultConnector: { name: 'rounded' }

plotly.js lag problem. my project is running slow

I have a project where I created the backend with flask. It reads the data from the csv file and transfers it to html. It reads data every second with Ajax. Then I visualize the data with plotly.js. With Ajax, every get operation comes with a delay.I am working with approximately 2000 data.
However, there is a delay in my code. How can I refactor this code? What can I do to avoid delay?
$(function requestData() {
$.ajax({
type: "GET",
url: "/deneme3",
success: function (data) {
//console.log('success',data);
//console.log('success',data[0]);
//console.log('success',data[1]);
var enlem = [];
var boylam = [];
var ch1 = [];
var ch2 = [];
var ch3 = [];
var ch4 = [];
enlem = data[0];
boylam = data[1];
ch1 = data[2];
ch2 = data[3];
ch3 = data[4];
ch4 = data[5];
//console.log('enlem',enlem);
//console.log('boylam',boylam);
var trace1 = {
x: enlem,
y: boylam,
mode: "markers",
marker: {
size: 10,
color: ch1,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
};
var data = [trace1];
var layout = {
title: "Scatter Plot with a Color Dimension",
};
Plotly.newPlot("tester", data, layout);
setInterval(function () {
var update = {
x: [[enlem]],
y: [[boylam]],
};
Plotly.extendTraces("tester", update, [0]);
}, 100);
//ch1 grafik
var trace2 = {
y: ch1,
type: "scatter",
};
var data2 = [trace2];
var layout2 = {
title: "CH1",
};
Plotly.newPlot("ch1", data2, layout2);
setInterval(function () {
var update = {
y: [[ch1]],
};
Plotly.extendTraces("ch1", update, [0]);
}, 100);
//ch2 grafik
var trace3 = {
y: ch2,
type: "scatter",
};
var data3 = [trace3];
var layout3 = {
title: "CH2",
};
Plotly.newPlot("ch2", data3, layout3);
setInterval(function () {
var update = {
y: [[ch2]],
};
Plotly.extendTraces("ch2", update, [0]);
}, 100);
//ch3 grafik
var trace4 = {
y: ch3,
type: "scatter",
};
var data4 = [trace4];
var layout4 = {
title: "CH3",
};
Plotly.newPlot("ch3", data4, layout4);
setInterval(function () {
var update = {
y: [[ch3]],
};
Plotly.extendTraces("ch3", update, [0]);
}, 100);
//ch4 grafik
var trace5 = {
y: ch4,
type: "scatter",
};
var data5 = [trace5];
var layout5 = {
title: "CH4",
};
Plotly.newPlot("ch4", data5, layout5);
setInterval(function () {
var update = {
y: [[ch4]],
};
Plotly.extendTraces("ch4", update, [0]);
}, 100);
},
});
setTimeout(requestData, 100);
});
Also, which of the Ajax and socketio would it make more sense to use?
As discussed in the comments, something like this might work: initialize empty plots, then just fill in data in the update function:
function plotData(data) {
const [enlem, boylam, ...chs] = data;
Plotly.extendTraces("tester", {
x: [[enlem]],
y: [[boylam]],
}, [0]);
for (let i = 0; i < 4; i++) {
const j = i + 1;
Plotly.extendTraces(`ch${j}`, {
y: [[chs[i]]],
}, [0]);
}
// After success, wait before loading more data
setTimeout(requestData, 1000);
}
function requestData() {
// Simulate a successful response that returns 6 numbers.
plotData([Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()]);
// If a real endpoint was available, you could do something like
/*$.ajax({
type: "GET",
url: "/deneme3",
success: plotData,
});*/
}
function initialize() {
Plotly.newPlot("tester", [{
x: [],
y: [],
mode: "markers",
marker: {
size: 10,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
}], {
title: "Scatter Plot with a Color Dimension",
});
for (let i = 1; i <= 4; i++) {
Plotly.newPlot(`ch${i}`, [{
y: [],
type: "scatter",
}], {
title: `CH${i}`,
});
}
requestData(); // Fire off first update
}
$(initialize);
div {
width: 33%;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script>
<div id="tester"></div>
<div id="ch1"></div>
<div id="ch2"></div>
<div id="ch3"></div>
<div id="ch4"></div>

animation of a graph of an equation javascript

I'm stuck on this issue and don't know where to put my hands.
I have to draw in javascript the animation of the graph of the equation y = x ^ 3
what do i mean?
knowing y (for example y = 10) I would like the graph to start from (0; 0) up to (x; 10) following the equation y = x ^ 3
also I would like to create a button which can be clicked during the animation and tells me what y is the graph at that precise moment
for now thanks to chart.js i managed to do this:
JS
var ctx = document.getElementById("myChart");
var data = {
labels: [1, 2, 3, 4, 5],
datasets: [
{
function: function(x) { return x*x*x },
borderColor: "rgba(153, 102, 255, 1)",
data: [],
fill: true
}]
};
Chart.pluginService.register({
beforeInit: function(chart) {
var data = chart.config.data;
for (var i = 0; i < data.datasets.length; i++) {
for (var j = 0; j < data.labels.length; j++) {
var fct = data.datasets[i].function,
x = data.labels[j],
y = fct(x);
data.datasets[i].data.push(y);
}
}
}
});
var myBarChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
HTML
<canvas id="myChart"></canvas>
result
for now I only have the graph, there is no animation and I cannot select the maximum y
how can I do?
To set max amount on your y Axes you can use the max property or suggestedMax if you want to make sure that if the data goes bigger the axis adapts. For the animation you can write custom logic as in the example underneath. I only dont know how to get the value its at on the click:
const labels = [1, 2, 3, 4, 5]
const totalDuration = 5000;
const delayBetweenPoints = totalDuration / labels.length;
const previousY = (ctx) => ctx.index === 0 ? ctx.chart.scales.y.getPixelForValue(100) : ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.index - 1].getProps(['y'], true).y;
var options = {
type: 'line',
data: {
labels,
datasets: [{
label: '# of Votes',
data: [],
borderWidth: 1,
function: function(x) {
return x * x * x
},
borderColor: 'red',
backgroundColor: 'red'
}]
},
options: {
scales: {
y: {
max: 250
}
},
animation: {
x: {
type: 'number',
easing: 'linear',
duration: delayBetweenPoints,
from: NaN, // the point is initially skipped
delay(ctx) {
if (ctx.type !== 'data' || ctx.xStarted) {
return 0;
}
ctx.xStarted = true;
return ctx.index * delayBetweenPoints;
}
},
y: {
type: 'number',
easing: 'linear',
duration: delayBetweenPoints,
from: previousY,
delay(ctx) {
if (ctx.type !== 'data' || ctx.yStarted) {
return 0;
}
ctx.yStarted = true;
return ctx.index * delayBetweenPoints;
}
}
}
},
plugins: [{
id: 'data',
beforeInit: function(chart) {
var data = chart.config.data;
for (var i = 0; i < data.datasets.length; i++) {
for (var j = 0; j < data.labels.length; j++) {
var fct = data.datasets[i].function,
x = data.labels[j],
y = fct(x);
data.datasets[i].data.push(y);
}
}
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
var chart = new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.1/chart.js" integrity="sha512-HJ+fjW1Hyzl79N1FHXTVgXGost+3N5d1i3rr6URACJItm5CjhEVy2UWlNNmFPHgX94k1RMrGACdmGgVi0vptrw==" crossorigin="anonymous"></script>
</body>

graph of an equation animated javascript (crash game)

i don't know how to get out of this problem
I have the animation of the graph of the equation y = x ^ 2
this:
const labels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
const totalDuration = 2000;
const delayBetweenPoints = totalDuration / labels.length;
const previousY = (ctx) => ctx.index === 0 ? ctx.chart.scales.y.getPixelForValue(100) : ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.index - 1].getProps(['y'], true).y;
var options = {
type: 'line',
data: {
labels,
datasets: [{
label: '# of Votes',
data: [],
borderWidth: 1,
function: function(x) {
return x * x
},
borderColor: "rgba(153, 102, 255, 1)",
fill: true
}]
},
options: {
scales: {
y: {
max: 200
},
x: {
suggestedMax: 210
}
},
animation: {
x: {
type: 'number',
easing: 'linear',
duration: delayBetweenPoints,
from: NaN, // the point is initially skipped
delay(ctx) {
if (ctx.type !== 'data' || ctx.xStarted) {
return 0;
}
ctx.xStarted = true;
return ctx.index * delayBetweenPoints;
}
},
y: {
type: 'number',
easing: 'linear',
duration: delayBetweenPoints,
from: previousY,
delay(ctx) {
if (ctx.type !== 'data' || ctx.yStarted) {
return 0;
}
ctx.yStarted = true;
return ctx.index * delayBetweenPoints;
}
}
}
},
plugins: [{
id: 'data',
beforeInit: function(chart) {
var data = chart.config.data;
for (var i = 0; i < data.datasets.length; i++) {
for (var j = 0; j < data.labels.length; j++) {
var fct = data.datasets[i].function,
x = data.labels[j],
y = fct(x);
data.datasets[i].data.push(y);
}
}
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
var chart = new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.1/chart.js" integrity="sha512-HJ+fjW1Hyzl79N1FHXTVgXGost+3N5d1i3rr6URACJItm5CjhEVy2UWlNNmFPHgX94k1RMrGACdmGgVi0vptrw==" crossorigin="anonymous"></script>
</body>
I have to add 3 things and I don't know how to get out of it
how can I define a Y value for which the line stops going up?
if this Y is bigger than the axis data, how can they adapt?
how can I create a button which when clicked tells me the exact Y value at that moment during the animation?
I wish something like this graph would come out:
https://www.youtube.com/watch?v=w48ahDZQPnQ
You can try setting the Y max value like this in your code to auto adjust Y axis scale.
beforeInit: function(chart) {
var data = chart.config.data;
let maxValue = 0;
for (var i = 0; i < data.datasets.length; i++) {
for (var j = 0; j < data.labels.length; j++) {
var fct = data.datasets[i].function,
x = data.labels[j],
y = fct(x);
if (maxValue < y) {
maxValue = y;
}
data.datasets[i].data.push(y);
}
}
chart.options.scales.y.max = maxValue;
}

JavaScript - Highcharts box plot not displaying

I am having trouble creating a highcharts box-plot graph, I have all the data in the correct format i.e. min, lower quartile, median, upper quartile and max.
I can display the categories but I cannot get it to display the data.
This is my code:
function BoxPlot() {
//ViewBag Variables
var Till = #Html.Raw(Json.Encode(#ViewBag.Tills));
var Per20 = #Html.Raw(Json.Encode(#ViewBag.P20));
var Per30 = #Html.Raw(Json.Encode(#ViewBag.P30));
var Per40 = #Html.Raw(Json.Encode(#ViewBag.P40));
var Per50 = #Html.Raw(Json.Encode(#ViewBag.P50));
var Per60 = #Html.Raw(Json.Encode(#ViewBag.P60));
var Per70 = #Html.Raw(Json.Encode(#ViewBag.P70));
var Per80 = #Html.Raw(Json.Encode(#ViewBag.P80));
var Per90 = #Html.Raw(Json.Encode(#ViewBag.P90));
//Combine the till no with its data
var final = [];
for(var i=0; i < Till.length; i++) {
final.push({
name: Till[i],
p20: Per20[i],
p30: Per30[i],
p40: Per40[i],
p50: Per50[i],
p60: Per60[i],
p70: Per70[i],
p80: Per80[i],
p90: Per90[i],
});
}
console.log(final)
//get the data into the correct format for box plot
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
a: final[i].p20,
b: ((final[i].p30 + final[i].p40) / 2),
c: ((final[i].p50 + final[i].p60) / 2),
d: ((final[i].p70 + final[i].p80) / 2),
e: final[i].p90,
});
}
console.log(formated)
//graph the data
$('#container').highcharts({
chart: {
type: 'boxplot'
},
title: {
text: 'Highcharts Box Plot'
},
legend: {
enabled: true
},
xAxis: {
categories: Till,
title: {
text: 'Till No.'
}
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Values',
data: formated,
tooltip: {
headerFormat: '<em>Till No. {point.key}</em><br/>'
}
}]
});
}
This is an example of the formatted array and the data it contains:
This is how the graph currently looks, you can see the categories array is working but it is not showing the data:
I was able to solve this by changing how I gathered the data, Im not sure if the box plot is case sensitive but by changing the variable names the data displayed
This is the whole code I am using:
function BoxPlot() {
//ViewBag Variables
var Till = #Html.Raw(Json.Encode(#ViewBag.Tills));
var Per20 = #Html.Raw(Json.Encode(#ViewBag.P20));
var Per30 = #Html.Raw(Json.Encode(#ViewBag.P30));
var Per40 = #Html.Raw(Json.Encode(#ViewBag.P40));
var Per50 = #Html.Raw(Json.Encode(#ViewBag.P50));
var Per60 = #Html.Raw(Json.Encode(#ViewBag.P60));
var Per70 = #Html.Raw(Json.Encode(#ViewBag.P70));
var Per80 = #Html.Raw(Json.Encode(#ViewBag.P80));
var Per90 = #Html.Raw(Json.Encode(#ViewBag.P90));
var heading = #Html.Raw(Json.Encode(#ViewBag.QueryTitle));
//Combine the till no with its data
var final = [];
for(var i=0; i < Till.length; i++) {
final.push({
name: Till[i],
p20: Per20[i],
p30: Per30[i],
p40: Per40[i],
p50: Per50[i],
p60: Per60[i],
p70: Per70[i],
p80: Per80[i],
p90: Per90[i],
});
}
console.log(final)
//get the data into the correct format for box plot
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
low: final[i].p20,
q1: ((final[i].p30 + final[i].p40) / 2),
median: ((final[i].p50 + final[i].p60) / 2),
q3: ((final[i].p70 + final[i].p80) / 2),
high: final[i].p90,
});
}
console.log(formated)
var boxData = [];
//boxData.push(formated);
//console.log(boxData);
//graph the data
$('#container').highcharts({
chart: {
type: 'boxplot'
},
title: {
text: heading
},
legend: {
enabled: true
},
xAxis: {
categories: Till,
title: {
text: 'Till No.'
}
},
yAxis: {
title: {
text: 'Distribution'
}
},
series: [{
name: 'Tills',
data:
formated
}]
});
}

Categories

Resources