Plotly: How to plot multiple lines with shared x-axis?

后端 未结 2 1177
温柔的废话
温柔的废话 2020-12-18 12:28

I would like to have a multiple line plot within same canvas tied with the same x-axis as shown something in the figure:

Using subplots does not achieve the i

相关标签:
2条回答
  • 2020-12-18 12:57

    Depending on the data you are plotting, I think you could either check out "Stacked Subplots with a Shared X-Axis (low-level API)" on https://plotly.com/python/subplots/

    Or separate the data by shifting each line plot upwards like so:

    import plotly.graph_objects as go
    import random
    
    
    data = []
    n = 9
    
    for x in range(10, 60, 10):
    
      points = [value + x for value in random.sample(range(1,n+1), k = n)]
      
      data.append(go.Scatter(y=points))
    
    fig = go.Figure(data = data)
    
    fig.show()
    
    0 讨论(0)
  • 2020-12-18 13:07

    With a dataset such as this you can select any number of columns, set up a figure using fig = make_subplots() with shared_xaxes set to True and then add your series with a shared x-axis using fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1) in a loop to get this:

    Let me know if this is a setup you can use but need a little tweaking.

    Complete code:

    import plotly.graph_objects as go
    import plotly.io as pio
    from plotly.subplots import make_subplots
    import pandas as pd
    
    # data
    pio.templates.default = "plotly_white"
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
    df = df.set_index('Date')
    df.tail()
    cols = df.columns[:-4]
    ncols = len(cols)
    
    # subplot setup
    fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)
    
    for i, col in enumerate(cols, start=1):
        fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1)
        
    fig.show()
    
    0 讨论(0)
提交回复
热议问题