Plotly:如何绘制具有共享 x 轴的多条线? [英] Plotly: How to plot multiple lines with shared x-axis?
问题描述
我想在同一个画布中绘制多条线图,并与相同的 x 轴绑定,如
使用子图并不能达到预期的目的.
import plotly.express as px从 plotly.subplots 导入 make_subplots导入 plotly.graph_objects as gofig = 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)图.show()
我可以知道如何做到这一点,如果有人能指出好的阅读材料不胜感激
使用数据集,例如
如果这是您可以使用但需要稍作调整的设置,请告诉我.
完整代码:
import plotly.graph_objects as go将 plotly.io 导入为 pio从 plotly.subplots 导入 make_subplots将熊猫导入为 pd# 数据pio.templates.default = "plotly_white";df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')df = df.set_index('日期')df.tail()cols = df.columns[:-4]ncols = len(cols)# 子图设置fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)对于 i, col in enumerate(cols, start=1):fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1)图.show()
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 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:
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()
这篇关于Plotly:如何绘制具有共享 x 轴的多条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!