问题描述
我想绘制一个带有数据集的多折线图(多个列表附加在 1 个列表中),其中我知道我将哪个作为 X 轴和 Y 轴。
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*/
该示例取自 here。我所看到的绘制每条线(此处为 2 次)的变量正在调用以设置数据。就我而言,Y 轴将出现大约 30 次,并且每个 X 轴的值都相同。但是我还没有找到可以使用 for 循环或类似方法附加 Y 轴值的动态解决方案。这意味着我只想调用这个 data
变量 1 次,并且想立即将多图表的所有信息附加到那里。
let dataSet = [[1,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>
所以,我想知道是否有任何方法可以通过以下方法在单个变量中添加多个时间轴(此处为 trace1
)。
解决方法
我已经明白(也许)我的不足之处。
1/ 起初我意识到我忽略了 traces or datapoints
的 plotly
是一个对象数组。
2/ 我也尝试整理我的数据
我在这里给出了我已经完成的解决方案。
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',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>