首页 > 解决方案 > 使用 Plotly.js 绘制两个条形图和两个散点图并共享相同的 x 轴

问题描述

我们希望使用一个图表来显示衡量指标的每一年的条形图,以及同一年的散点图(或线)。默认情况下,这似乎会创建两次 x 轴标签。

此外,它似乎也在 2016 年和 2017 年之间插入 2016.5 (这显然没有意义)。

注意:我们正在使用 angular-plotly

标签: plotlyplotly.js

解决方案


这是您所描述的内容的一个简单示例。如您所见,只有一个 x 轴标签。

Angular-plotly也有几乎完全相同的例子——只是度量不同,但没有什么能阻止你在 的两个元素中拥有x和相同的:ydata

import { Component } from '@angular/core';

@Component({
    selector: 'plotly-example',
    template: '<plotly-plot [data]="graph.data" [layout]="graph.layout"></plotly-plot>',
})
export class PlotlyExampleComponent {
    public graph = {
        data: [
            { x: [1, 2, 3], y: [2, 6, 3], type: 'scatter', mode: 'lines+points', marker: {color: 'red'} },
            { x: [1, 2, 3], y: [2, 5, 3], type: 'bar' },
        ],
        layout: {width: 320, height: 240, title: 'A Fancy Plot'}
    };
}

来自 github 文档的精美情节

如果这不是您要查找的内容,请提供您的代码。

编辑:

回答评论,为避免小数刻度,您可以通过提供如下布局将轴刻度限制为 x 值数组(我也更新了 codepen):

var trace1 = {
  x: [2000, 2001, 2002, 2003, 2004, 2005],
  y: [1.5, 1, 1.3, 0.7, 0.8, 0.9],
  type: 'scatter'
};

var trace2 = {
  x: [2000, 2001, 2002, 2003, 2004, 2005],
  y: [1.5, 1, 1.3, 0.7, 0.8, 0.9],
  type: 'bar'
};

var data = [trace1, trace2];

var layout = {
                xaxis:{
                  type: 'dates',
                  tickangle: 0,
                  tickvals: trace1.x
                }            
              };

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

推荐阅读