简体   繁体   English

Plotly:如何 plot 多条线与共享 x 轴?

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

I would like to have a multiple line plot within same canvas tied with the same x-axis as shown something in the figure :我想在同一个 canvas 内有一条多行 plot 与同一个 x 轴绑定,如图所示

在此处输入图像描述

Using subplots does not achieve the intended desire.使用子图并不能达到预期的目的。

import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=2, shared_xaxes=True,vertical_spacing=0.1)
fig.add_scatter(y=[2, 1, 3], row=1, col=1)
fig.add_scatter(y=[1, 3, 2], row=2, col=1)
fig.show()

May I know how this can be done, appreciate if someone can point to good reading material我可以知道如何做到这一点,如果有人能指出好的阅读材料,不胜感激

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:使用这样的数据集,您可以 select 任意数量的列,使用fig = make_subplots()设置一个图形, shared_xaxes设置为True ,然后使用fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1)在一个循环中得到这个:

在此处输入图像描述

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()

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/根据您绘制的数据,我认为您可以查看https://plotly.com/python/subplots/上的“具有共享 X 轴(低级 API)的堆叠子图”

Or separate the data by shifting each line plot upwards like so:或者通过向上移动每行 plot 来分离数据,如下所示:

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()

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

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