How to plot two plots in the same figure in plotly.js - javascript

I want to plot 2 plots in the same figure using plotly.js. I have gone through the documentation of plotly.js but was unable to find it. Can any body help?
Here is the code snippet:
First Plot:
var data4 = [ {
z: z,
x: x,
y: y,
type: 'contour'
}
];
var layout = {
title: 'Simple Contour Plot'
}
Plotly.newPlot('visualization2', data4, layout);
Second Plot:
var trace = {
x: x11,
y: x21,
mode: 'lines+markers'
};
var data3 = [ trace];
var layout = {
title:'Line and Scatter Plot',
height: 400,
width: 480
};
Plotly.newPlot('visualization3', data3, layout);
I want to plot these two in one figure. Note: The first one is a contour plot and the second one is a Line plot.

You have the ability to put a number of traces into your data that you wish to plot and it will plot them.
You also can only have 1 title per graph, however, you can have multiple axis titles.
var firstPlotTrace = {
z: z,
x: x,
y: y,
type: 'contour'
name: 'yaxis data'
};
var secondPlotTrace = {
x: x11,
y: x21,
mode: 'lines+markers'
name: 'yaxis2 data'
};
var plotData = [firstPlotTrace, secondPlotTrace];
var layout = {
title: 'Double Plot Title',
height: 400,
width: 400,
yaxis: {title: 'Simple Contour Plot Axis', range: [-20, 20]}
yaxis2: {title: 'Line and Scatter Plot Axis', range: [-20, 20]}
};
Plotly.newPlot('plotDiv', plotData, layout);
HTML -
<div id="plotDiv" style="height: 400px; width: 400px;"></div>

Related

How show a circular progress chart with Plotly Javascript

I am new to using the Plotly library and this time I find myself with the need to show in Vuejs 2 a circular progress graph like the following one.
I know that plotly is very complete but I have not seen an example with a similar aspect and that is also with javascript.
Thanks in advance for any information or help you can provide.
Greetings!
With plotly Derek Example, the graph looks like this
My English is not very good, but note that the line of the circle does not have a smooth curvature.
You can use plotly.js traces and text to recreate the components of this chart. If you use a scatter to place down an array of markers, you can create the grey arc, then place the red arc over it. To calculate the coordinates of each these markers, you can center your axes at (0,0) then use x=r*cos(theta) and y=r*sin(theta) where theta is your angle in radians. You can get an array of x and y values to trace out the desired portions of the red and grey arcs.
To get the circular chart to look like yours, I set the range of the x-axes and y-axes both to [-2,2], made the radius of the circular arcs 0.9 with [0,0] as the center, set the markers for these arcs to be size 10, and made the grey arc go from 210 to 85 degrees and red arc go from 90 to -200 degrees (using the function makeArr written by mhodges in his answer here),. Then to get the green marker to display in the legend, I created a trace with a green marker but with null values so it doesn't plot anything on the chart. Text traces can be used to add text around the center of the circular arcs.
Here is an example (codepen is here):
// credit goes to mhodges: https://stackoverflow.com/a/40475362/5327068
function makeArr(startValue, stopValue, cardinality) {
var arr = [];
var step = (stopValue - startValue) / (cardinality - 1);
for (var i = 0; i < cardinality; i++) {
arr.push(startValue + (step * i));
}
return arr;
}
// The function returns two arrays of circle coordinates
// for the outer points of a circle centered at some (x,y)
// and with a radius r with an arc of theta values
function getCircleCoords(r, center, degree_values) {
var center_x=center[0]
var center_y=center[1]
var x_coords = []
var y_coords = []
for (var i = 0; i < degree_values.length; i++) {
x_coords.push(center_x + (r * Math.cos(degree_values[i]*Math.PI/180)));
y_coords.push(center_y + (r * Math.sin(degree_values[i]*Math.PI/180)));
}
return [x_coords,y_coords]
}
var trace1 = {
x: [0],
y: [0.15],
text: ['1000'],
mode: 'text',
textfont: {
family: 'arial',
size: 28,
color: 'black'
},
showlegend: false
};
var trace2 = {
x: [0],
y: [-0.15],
text: ['kW/kg'],
mode: 'text',
textfont: {
family: 'arial',
size: 22,
color: 'grey'
},
showlegend: false
};
circleCoords = getCircleCoords(r=0.9, center=[0,0], radian_values=makeArr(90,-200,1000))
backgroundCircleCoords = getCircleCoords(r=0.9, center=[0,0], radian_values=makeArr(210,85,1000))
// display a marker in the legend without plotting it
var trace3 = {
x: [null],
y: [null],
mode: 'markers',
marker: {color: 'green', size: 10},
name: 'Correcto funcionamiento'
};
// grey background circle
var trace4 = {
x: backgroundCircleCoords[0],
y: backgroundCircleCoords[1],
mode: 'markers',
marker: {color: '#eeeeee', size: 10},
name: null,
showlegend: false
};
// red foreground circle
var trace5 = {
x: circleCoords[0],
y: circleCoords[1],
mode: 'markers',
marker: {color: 'red', size: 10},
name: 'Funcionamiento erroneo'
};
var layout = {
title:'RelacĂ­on potencia peso',
xaxis: {
range: [-2, 2],
zeroline: false,
showgrid: false,
zeroline: false,
showline: false,
showticklabels: false
},
yaxis: {
range: [-2, 2],
showgrid: false,
zeroline: false,
showline: false,
showticklabels: false
},
width: 600,
height: 600,
legend: {
x: 0,
y: 0,
"orientation": "h"
}
};
var data = [trace1, trace2, trace3, trace4, trace5];
Plotly.newPlot('myDiv', data, layout);
EDIT: for a smoother circle, you can increase the number of markers used to draw the circle.
circleCoords = getCircleCoords(r=0.9, center=[0,0], radian_values=makeArr(90,-200,5000))
backgroundCircleCoords = getCircleCoords(r=0.9, center=[0,0], radian_values=makeArr(210,85,5000))

Plotly line chart - multiple lines

I want to create a line chart with three lines (male,female,unknown). This is a sample of my data:
timestamp;sex;number
06:00;male;5
07:00;male;2
07:00;unkown;3
07:00;female;4
09:00;female;4
Is there a option in plotly to automatically create the three lines or do I need to loop through the data and create three traces by myself? This is my code so far:
var trace1 = {
type: 'scatter',
x: x,
y: y,
name: "Male",
transforms: [{
type: 'aggregate',
groups: x,
aggregations: [
{target: 'y', func: 'count', enabled: true},
]
}]
};
var data = [trace1];
Plotly.newPlot('myDiv', data, {title: 'Plotting CSV data from AJAX call'});
You need to create different data set(trace) for each category.
Maybe this can help you.
var men = {
x: x,
y: y,
type: 'scatter',
name:'male'
};
var female = {
x: x,
y: y,
type: 'scatter',
'name':'female'
};
var unknown = {
x: x,
y:y,
type: 'scatter',
'name':'unknown'
};
var data = [men, female,unknown];

plotly.js waterfall chart with different colors for up and down

I want to create a waterfall chart using plotlyjs which shows ups and downs as compared to its previous value. Up should be represented by green color and down with red color.
How can I create such a graph using plotly.js?
The example given on the plotly site has different colors for different value ranges and it has no connection with ups and downs.
You can actually pass an array of colors to Plotly.
If you have an array of value differences, like [200, 400, -300, -150, -150], then you can formulate a color array like below.
const labels = ["Apples", "Oranges", "Rent", "Water", "Profit"];
const values = [200, 400, -300, -150, -150];
const colors = values.map((v) => v > 0 ? 'rgba(55,128,191,1.0)' : 'rgba(219, 64, 82, 1.0)');
// Use the cumulative sum to calculate the baseline of each bar. Use this to create a stacked bar chart with white bars below and colored bars on top
const baseline = new Array(values.length);
values.reduce((sum, val, idx) => {
baseline[idx] = val > 0 ? sum : sum + val;
return sum + val;
}, 0);
const trace1 = {
x: labels,
y: baseline,
marker: {
color: 'rgba(1,1,1,0.0)'
},
type: 'bar'
};
const trace2 = {
x: labels,
y: values.map(Math.abs),
marker: {
color: colors
},
type: 'bar'
};
var layout = {
title: 'Annual Profit 2018',
barmode: 'stack',
paper_bgcolor: 'rgba(245,246,249,1)',
plot_bgcolor: 'rgba(245,246,249,1)',
width: 600,
height: 600,
showlegend: false,
annotations: []
};
Plotly.newPlot('plot', [trace1, trace2], layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="plot"></div>

plotly js: location and length of color scale in heatmap

Using plotly.js, you can make a heatmap, and the heatmap comes with a color scale on the right side, as do some of the 3d charts.
Here is an example in codepen.
Plotly.d3.json('https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json', function(figure) {
var data = [{
z: figure.z,
colorscale: 'Jet',
type: 'heatmap'
}
];
var layout = {title: 'Jet'};
Plotly.newPlot('myDiv', data, layout);
});
I am struggling to see if the api allows the color scale location and length to be modified. Does plotly.js allow manipulation of these attributes, and do you have an example of this for a heatmap and/or 3d graph?
You can set the position and length of the colorbar by adding the following line to your data:
colorbar: {x: -.5, len: 0.5}
Below is a snippet with a colorbar pushed to the left and half the regular size.
Plotly.d3.json('https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json', function(figure) {
var data = [{
z: figure.z,
colorscale: 'Jet',
type: 'heatmap',
colorbar: {x: -.5, len: 0.5}
}
];
var layout = {title: 'Jet'};
Plotly.newPlot('myDiv', data, layout);
});
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;"></div>
Adding this answer to show more tweaks you can do on Plotly colorbar
var plotData8kW = [{
z: data8kW,
hoverinfo:"z",
colorbar:{
// len: 0.35, //Change size of bar
title: 'Speed(RPM)<br\><br\>', //set title
titleside:'top', //set postion
//tickvals:[0,50,100],
titlefont: {color: 'blue'} //title font color
},
type: 'heatmap',
colorscale: enhancedScale,
},
];

Long tick labels getting cut off in plotly.js chart

Is it possible to give more room for tick labels in plotly.js? Long labels in my charts are getting cut off.
HTML:
<div id="plot"></div>
JavaScript:
var data = [{
type: 'bar',
x: [20, 14, 23],
y: ['giraffes', 'orangutans', 'a looooooooong string'],
orientation: 'h'
}];
var layout = {
title: 'Bar Chart'
};
Plotly.newPlot('plot', data, layout);
I can't see how to do this in the API for y-axes tick settings.
Given the nature of my charts, I need to use a horizontal orientation. So a solution I can't use is a vertical orientation with ticks rotated 90 degrees.
Update: plotly added support for automargins (see https://github.com/plotly/plotly.js/pull/2243), via the .axis.automargin configuration option.
To use, you'd change:
var layout = {
title: 'Bar Chart'
};
to:
var layout = {
title: 'Bar Chart',
yaxis: {
automargin: true
}
};
For more information, see https://plot.ly/javascript/axes/
Original Answer:
You can adjust the margins of plotly charts to give yourself some more space. For instance, change:
var layout = {
title: 'Bar Chart'
};
to
var layout = {
title: 'Bar Chart',
margin: {
l: 200
}
};
you can read more about adjusting margins here: https://plot.ly/javascript/setting-graph-size/
and overall layout options here: https://plot.ly/javascript/#layout-options
You can also set margin dynamically, based on label length:
var maxLabelLength = d3.max(data, d => d3.max(d.y, label => label.length));
const letterWidth = 7;
var layout = {
title: 'Bar Chart',
margin:{
l: maxLabelLength * letterWidth
}
};

Categories

Resources