简体   繁体   English

Plotly.js:覆盖两个具有相同 x 轴和不同 y 轴刻度的不同图形

[英]Plotly.js : Overlaying two different graphs with same x-axis and different y-axis scales

I have a scenario in my application while using Plotly.js where I need to overlay two different line graphs in the same plane, with the same x-axis and different y-axis scales, stacked on top of each other as shown in the image below.我在使用 Plotly.js 时在我的应用程序中有一个场景,我需要在同一平面上叠加两个不同的线图,具有相同的 x 轴和不同的 y 轴刻度,如图所示堆叠在彼此的顶部以下。 I imagine it to look something like this:我想它看起来像这样: 在此处输入图像描述

How can I do this?我怎样才能做到这一点?

You can create a secondary yaxis, then set the range of the primary and secondary yaxes differently, and also set which tickmarks are displayed for each of the yaxes.您可以创建辅助 yaxis,然后设置不同的主要和辅助 yaxes 的范围,并设置为每个 yaxes 显示哪些刻度线。 To make things a bit more generlizeable, I included a function that creates linearly spaced arrays that you can use for tickmarks, and some scaling factors for the min and max of the yaxis ranges.为了使事情更通用,我包含了一个 function,它创建了可用于刻度线的线性间隔 arrays,以及一些用于 y 轴范围的最小值和最大值的缩放因子。

You can view the codepen here .您可以在此处查看 codepen。

function linspace(start, stop, num, endpoint = true) {
    const div = endpoint ? (num - 1) : num;
    const step = (stop - start) / div;
    return Array.from({length: num}, (_, i) => start + step * i);
}

var yaxis_data = [40, 50, 60];
var yaxis2_data = [4,5,6];

var yaxis_data_min = Math.min(...yaxis_data);
var yaxis_data_max = Math.max(...yaxis_data);

var yaxis2_data_min = Math.min(...yaxis2_data);
var yaxis2_data_max = Math.max(...yaxis2_data);

var yaxis_data_range = [0.5*yaxis_data_min, yaxis_data_max];
var yaxis2_data_range = [yaxis2_data_min, 1.5*yaxis2_data_max];

var yaxis_ticks = linspace(yaxis_data_min, yaxis_data_max, 3)
var yaxis2_ticks = linspace(yaxis2_data_min, yaxis2_data_max, 3)

var trace1 = {
  x: [1, 2, 3],
  y: yaxis_data,
  name: 'yaxis data',
  type: 'scatter'
};

var trace2 = {
  x: [2, 3, 4],
  y: yaxis2_data,
  name: 'yaxis2 data',
  yaxis: 'y2',
  type: 'scatter'
};

var data = [trace1, trace2];

var layout = {
  title: 'Double Y Axis Example',
  yaxis: {
    title: 'yaxis title',
    range: yaxis_data_range,
    tickvals: yaxis_ticks
  },
  yaxis2: {
    title: 'yaxis2 title',
    titlefont: {color: 'rgb(148, 103, 189)'},
    tickfont: {color: 'rgb(148, 103, 189)'},
    overlaying: 'y',
    side: 'right',
    range: yaxis2_data_range,
    tickvals: yaxis2_ticks
  }
};

Plotly.newPlot('myDiv', data, layout);

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM