append multiple y axis data in plotly JS - javascript

I want to draw a multiline chart with a dataSet(multiple lists append in 1 list) where I know which one I will as X-axis and Y-axis.
let dataSet = [[1, 2, 3, 4], [10, 15, 13, 17], [16, 5, 11, 9]];
/**
X-axis = dataSet[0]
The remaining will be used as Y-axis*/
The example is taken from here. Where I have seen for plotting each line(here 2 times) variable is calling to set the data. In my case, Y-axis will appear near about 30 times and for each X-axis value will be the same. But I haven't found a dynamic solution where I can append the Y-axis value using a for loop or something like that. That means I want to call this data variable only 1 time and want to append all information of multi-chart there at instant.
I have added my approach here.
let dataSet = [[1, 2, 3, 4], [10, 15, 13, 17], [16, 5, 11, 9]];
function get_val (data){
let x = [];
for(let j = 1;j<data.length;j++)
{
x.push(data[j]);
}
//console.log("x: ",x);
return x;
}
var trace1 = {
x: dataSet[0],
y: get_val(dataSet), /* if write here get_val(dataSet)[0] then works fine*/
type: 'scatter'
};
/**
if you uncomment the following lines, result will be as like as the example of plotly JS
*/
/*
var trace2 = {
x: dataSet[0],
y: get_val(dataSet)[1],
type: 'scatter'
};
*/
var data = [trace1/*, trace2*/];
Plotly.newPlot('myDiv', data);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
So, I want to know is there any approach by following which I can add multiple time any axis within a single variable(here trace1).

I have understood(maybe) where was my lacking.
1/ At first I have realized that I have overlooked that the traces or datapoints of plotly is an array of objects.
2/ I have also tried to organize my data
I have given here the solution that I have done.
let dataSet = [[10, 20, 30, 40], [10, 15, -13, 17], [1-6, 5, 11, 20] ]
/** following function will take the data and return the dataTRace as per as plotly's requirements.*/
function make_trace({data, set_type = "scatter", set_mode = "lines"} = {}){
let dataPoint = [];
for(let i = 1; i<data.length; i++){
dataPoint.push({
x: data[0],
y: data[i],
mode: set_mode,
type: set_type,
name: 'y_' + i
});
}
return dataPoint;
}
/** following function will make the layout for the plot*/
function make_layout({given_title="the title is not provided",x_min=0,x_max=15,x_axis_title="x_axis", y_min=0,y_max=15, y_axis_title="y_axis"} = {})
{
let layout_object = {
title: {
text: given_title
},
showlegend: true,
xaxis: {
range: [x_min, x_max],
title: x_axis_title
},
yaxis: {
range: [y_min, y_max],
title: y_axis_title
},
};
return layout_object;
}
let fig_layout = make_layout({given_title:"x vs y1, y2 plot",
x_min: 10, x_max : 50, x_axis_title:"x",
y_min: -20, y_max: 20, y_axis_title : "y(1,2)"});
Plotly.newPlot('myDiv', make_trace({data : dataSet, set_type:"scatter", set_mode : "lines"}), fig_layout);
Plotly.newPlot('myDiv_1', make_trace({data : dataSet, set_type:"scatter", set_mode : "markers"}), fig_layout);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
<div id='myDiv_1'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>

Related

Identify Subplots in Plotly

Is it possible to identify in which subplot my mouse is ? I got a function with which i can add points to my trace, but my problem is that this point gets shown in both subplots as soon as i add one, that's why i'd like to be able to get the number/the name of my subplot to differentiate in which subplot an even has fired.
So its important for me to figure out in which subplot an event has fired.
Here is an example of Plotly with two subplots with a click function. Instead of showing me the data in the plots, it would be important for me to see in which subplot it have clicked !
var trace1 = {
x: [1, 2, 3],
y: [4, 5, 6],
type: 'scatter'
};
var trace2 = {
x: [20, 30, 40],
y: [50, 60, 70],
xaxis: 'x2',
yaxis: 'y2',
type: 'scatter'
};
var data = [trace1, trace2];
var layout = {
grid: {rows: 1, columns: 2, pattern: 'independent'},
};
var myPlot = document.getElementById('myDiv')
Plotly.newPlot(myPlot, data, layout);
myPlot.on('plotly_click', function(data){
var pts = '';
for(var i=0; i < data.points.length; i++){
pts = 'x = '+data.points[i].x +'\ny = '+
data.points[i].y.toPrecision(4) + '\n\n';
}
alert('Closest point clicked:\n\n'+pts);
});
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-2.3.1.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
From looking at the MouseEvent data it seems you can identify a subplot using:
myPlot.on('plotly_click', function (data) {
console.log(data.event.target.dataset.subplot)
});
Clicking on the first subplot logs xy. Clicking on the second subplot logs x2y2.

Plotly color not changing Javascript

I working on a project that needs me to use graph csv file inputs. I've been using plotly and so far it seems to be working very well.
However, when I try to change the color of the graphs (lines and markers) it doesn't work. I am posting excerpts of my code since the color is overall a small portion of the code and I don't want to dump everything here.
//There's multiple charts so changing color is important
var r = Math.random() * 256
var g = Math.random() * 256
var b = Math.random() * 256
...
//used these as a vars so I can change things to test easily (multiple time series being used)
var color='rgb('+r+', '+g+', '+b+')'
var colora='rgba('+r+', '+g+', '+b+', '+'0.14'+')'
...
//layout of markers
{
x: time,
y: time,
z: data1,
line: {
reversescale: false,
//color: "'"+color+"'"
color: "'rgb("+r+', ' +g+', '+ b+")'",
},
//mode: 'lines',
marker: {
//color: "'"+color+"'",
color: "'rgb("+r+', ' +g+', '+ b+")'",
size: 3,
line: {
//color: "'"+colora+"'",
color: "'rgb("+r+', ' +g+', '+ b+")'",
width: 0.1
},
opacity: 0.8
},
type: 'scatter3d'
}
Both the attempts just give me the standard black dots. When I tried constants that worked fine (something like color:'rgb(100,100,240)'). Is there something I'm missing here? I've console.logged this thing and it doesn't seem to be an issue with the structure of my vars.
You have too many quotation marks around your rgb strings. In order to avoid confusion when concatenating strings, you could also use template strings.
See the working fiddle below.
const r = 0;
const g = 255;
const b = 0;
const color = 'rgb(' + r + ',' + g + ',' + b + ')';
const colorTemplate = `rgb(${r},${g},${b})`;
var trace1 = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter',
marker: {
color: color
}
};
var trace2 = {
x: [1, 2, 3, 4],
y: [16, 5, 11, 9],
type: 'scatter',
marker: {
color: colorTemplate
}
};
var data = [trace1, trace2];
Plotly.newPlot('myDiv', data);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
The problem with my code is that I'm using vars. By switching to consts, I can fix the thing. I didn't catch the color not changing because for some reason the legend was displaying the right colors, but the markers and lines don't accept it.

How to make Plotly.js listen the click events of the tick labels?

So, in this dynamic chart, I want to change the Y-axis' min and max values when any of the Y-axis' Tick Label is clicked.
You could add a d3 event listener to all y-ticks and make sure that the SVG group gets all the events.
Wrapping the whole snippet in Plotly's afterplot event makes sure that the event listener does not get lost after updating the graph.
var trace1 = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter'
};
var trace2 = {
x: [1, 2, 3, 4],
y: [16, 5, 11, 9],
type: 'scatter'
};
var data = [trace1, trace2];
var myPlot = document.getElementById('myDiv');
Plotly.newPlot(myPlot, data);
myPlot.on('plotly_afterplot', function(){
Plotly.d3.selectAll(".yaxislayer-above").selectAll('text')
.on("click", function(d) {
alert("Hello, I am " + d.x);
});
});
.yaxislayer-above {
cursor: pointer;
pointer-events: all;
}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>

js chart non uniform x values

Is there a JS Charting lib that supports multiple curces, having unequal steps?
Consider data like that:
Curve 1 (x/y pairs) RED in Sample:
[1, 10] [10, 20] [20,20]
Curve 2 Green in Sample:
[1, 2] [5, 6] [10,10] [11,12] [15,15] [20,20]
This should result in 2 Curves with x RANGE from 1..20. The first only has 3 data points that should be connected by a line. The second has 6 Points in the same x value range.
Which JS Charting library can handle that?
most likely, any chart lib can handle,
just need to load the data in the format the chart accepts
here, google charts is used to draw the chart
google charts has a method to join tables
so, just create two data tables, one for each x range
the resulting joined table will fill in the missing values with null
as such, need option for interpolateNulls so there are no breaks in the lines
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var x0 = [
[1, 10], [10, 20], [20,20]
];
var x1 = [
[1, 2], [5, 6], [10,10], [11,12], [15,15], [20,20]
];
var data0 = google.visualization.arrayToDataTable(x0, true);
var data1 = google.visualization.arrayToDataTable(x1, true);
var joinData = google.visualization.data.join(
data0, data1, 'full', [[0, 0]], [1], [1]
);
var options = {
height: 400,
interpolateNulls: true,
legend: {
position: 'none'
},
vAxis: {
viewWindow: {
max: 30
}
},
hAxis: {
viewWindow: {
max: 30
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(joinData, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to remove paddings in Bar chart? (Chart.JS)

Is it possible to remove paddings inside bar chart?
<canvas id="weeksChartFallout" width="660" height="200"></canvas>
var falloutArray = [12, 24, 20, 15, 18, 20, 22, 10, 10, 12, 14, 10, 16, 16];
var dataWeeksFallouts = {
labels: ["16.02", "17.02", "18.02", "19.02", "20.02", "21.02", "22.02", "23.02", "24.02", "25.02", "26.02", "27.02", "28.02", "01.03"],
datasets: [
{
label: "Fallouts",
fillColor: "rgba(63,107,245,0.67)",
data: falloutArray
}
]
};
var fc = document.getElementById('weeksChartFallout').getContext('2d');
window.weeksChartFallout = new Chart(fc).Bar(dataWeeksFallouts,{
barShowStroke : false,
barValueSpacing : 4, //distance between bars
barValueWidth: 20,
scaleShowLabels: false,
scaleFontColor: "transparent",
tooltipEvents: []
});
I mean space between first bar and left line and, especially space between last Bar and end of the chart (screenshot).
Here is my Fiddle
The x scale left and right paddings are calculated in the calculateXLabelRotation. If you have only these kind of charts you could simply replace this function to return no padding, like below
var originalCalculateXLabelRotation = Chart.Scale.prototype.calculateXLabelRotation
Chart.Scale.prototype.calculateXLabelRotation = function () {
originalCalculateXLabelRotation.apply(this, arguments);
this.xScalePaddingRight = 0;
this.xScalePaddingLeft = 0;
}
Fiddle - http://jsfiddle.net/ov9p5qhz/
Note that there is still some spacing on the left and right - that comes from your barValueSpacing: 4 option.
If you have other charts on the page that you don't want to keep separate, use Chart.noConflict()

Categories