Plotly:如何向 plotly express 图形添加水平滚动条?

Plotly: How to add a horizontal scrollbar to a plotly express figure?

我开始学习更多关于 plotly 和 pandas 的知识,并且我有一个多变量时间序列,我希望使用 plotly.express 特征来绘制和交互。我还希望我的绘图为水平滚动条,以便初始绘图用于预先指定的初始时间间隔。这是我的示例,涉及三个时间序列和 100K 个时间点:

import plotly.express as px
import numpy as np
import pandas as pd

np.random.seed(123)
e = np.random.randn(100000,3)  
df=pd.DataFrame(e, columns=['a','b','c'])

df['x'] = df.index
df_melt = pd.melt(df, id_vars="x", value_vars=df.columns[:-1])
fig=px.line(df_melt, x="x", y="value",color="variable")
fig.show()

(出于我的最终目的,时间序列会更大——在 900K+ 个时间点中可能有 40 到 70 个时间序列。)

这会创建一个图表,我可以使用 plotly.express 功能(例如缩放、平移、矩形选择等)与之交互

有没有一种方法可以增强它,使初始图仅显示前 500 个时间点,并且滚动条允许我调查随着时间的增加会发生什么?

在 IDLE 中使用 Mac OS 10.15.4 和 Python 3.7。我希望在 IDLE 中而不是在 Jupyter notebook 环境中创建它。

最简单的方法是将以下内容添加到您的设置中:

fig.update_layout(xaxis=dict(rangeslider=dict(visible=True),
                             type="linear"))

你会得到:

这将使您能够对原始图形进行子集和平移:

完整代码:

import plotly.express as px
import numpy as np
import pandas as pd

np.random.seed(123)
e = np.random.randn(100000,3)  
df=pd.DataFrame(e, columns=['a','b','c'])

df['x'] = df.index
df_melt = pd.melt(df, id_vars="x", value_vars=df.columns[:-1])
fig=px.line(df_melt, x="x", y="value",color="variable")

# Add range slider
fig.update_layout(xaxis=dict(rangeslider=dict(visible=True),
                             type="linear")
)

fig.show()

使用plotly.graphing_objects离线使用plotly

您也可以按如下方式使用 plotly.graphing_objects

引用 official documentation 中的以下示例。

import plotly.graph_objects as go

import pandas as pd

# Load data
df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df.columns = [col.replace("AAPL.", "") for col in df.columns]

# Create figure
fig = go.Figure()

fig.add_trace(
    go.Scatter(x=list(df.Date), y=list(df.High)))

# Set title
fig.update_layout(
    title_text="Time series with range slider and selectors"
)

# Add range slider
fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label="1m",
                     step="month",
                     stepmode="backward"),
                dict(count=6,
                     label="6m",
                     step="month",
                     stepmode="backward"),
                dict(count=1,
                     label="YTD",
                     step="year",
                     stepmode="todate"),
                dict(count=1,
                     label="1y",
                     step="year",
                     stepmode="backward"),
                dict(step="all")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
)

fig.show()