情节:如何在情节表达图形上添加水平滚动条?

时间:2020-05-13 18:54:02

标签: python plotly

我开始学习更多有关plotly和pandas的信息,并希望使用一个多变量时间序列来绘制和使用plotly.express功能进行交互。我还希望将绘图放置在水平滚动条上,以便初始绘图用于预先指定的初始时间间隔。这是我的示例,涉及三个时间序列以及10万个时间点:

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

enter image description here

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

这将创建一个图形,我可以使用plotly与之交互。表达诸如缩放,平移,矩形选择等功能。

有没有一种方法可以扩大此范围,以便初始图仅显示前500个时间点,并且滚动条允许我调查随着时间增加会发生什么情况?

使用带有IDLE的Mac OS 10.15.4和Python 3.7。我希望在IDLE中而不是在Jupyter笔记本环境中创建此文件。

2 个答案:

答案 0 :(得分:4)

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

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

您将得到:

enter image description here

这将使您能够子集并平移原始图形:

enter image description here

完整代码:

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

答案 1 :(得分:2)

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

enter image description here