在Plotly Python中用时间滑块绘制连续的直方图

时间:2017-03-20 08:39:24

标签: python histogram plotly

我每天从数据生成两个直方图,一个具有所需的值,另一个具有不同工作站的达到值。我想并排绘制这些直方图,如底部粉红色示例in Plotly here(参见源代码链接)。但是,由于两个直方图都是每天生成的,我需要在图表中添加时间滑块,如底部示例'Simple Slider' from Plotly(参见源代码链接)。

我的问题是第一个例子使用

fig = dict(data=data, layout=layout)
plotly.offline.plot(fig, filename='Sine Wave Slider')

绘制直方图,而滑块使用以下内容:

import plotly.graph_objs as go
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename='styled histogram')

我现在的(不正常)代码看起来像这样,我尝试将相同的2个直方图绘制3次。如何更改代码以生成同时使用直方图(两者都具有不同的随机数据)和滑块的图形?

import plotly
import plotly.graph_objs as go
import numpy as np

x0 = np.random.randn(500)
x1 = np.random.randn(500)+1

trace1 = go.Histogram(
    x=x0,
    histnorm='count',
    name='control',
    autobinx=False,
    xbins=dict(
        start=-3.5,
        end=3.0,
        size=0.5
    ),
    marker=dict(
        color='#FFD7E9',
    ),
    opacity=0.75
)
trace2 = go.Histogram(
    x=x1,
    name='experimental',
    autobinx=False,
    xbins=dict(
        start=-2.0,
        end=5,
        size=0.5
    ),
    marker=dict(
        color='#EB89B5'
    ),
    opacity=0.75
)
data = [trace1, trace2]

layout = go.Layout(
    title='Sampled Results',
    xaxis=dict(
        title='Value'
    ),
    yaxis=dict(
        title='Count'
    ),
    bargap=0.2,
    bargroupgap=0.1
)

steps = []
for i in range(len(trace1)):
    step = dict(
        method = 'restyle',
        args = ['visible', [False] * len(trace1)],
    )
    step['args'][1][i] = True # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active = 20,
    currentvalue = {"prefix": "Frequency: "},
    pad = {"t": 3},
    steps = steps
)]

layout = dict(sliders=sliders)
fig = dict(data=data, layout=layout)
plotly.offline.plot(fig, filename='Histogram Slider')

1 个答案:

答案 0 :(得分:4)

  • 你可以创建一个直方图列表,比方说3天(total_days = 3,奇数是实验性的,偶数是控制的)。
  • 仅显示第一条痕迹(visible = day < 1)。
  • 滑块中的每个步骤都会显示/隐藏另一对痕迹。

enter image description here

import plotly
import numpy as np
plotly.offline.init_notebook_mode()

total_days = 3

data = list()

for day in range(total_days):
    data.append(plotly.graph_objs.Histogram(
        x=np.random.randn(500) + day * 0.5,
        histnorm='count',
        name='Day {}, control'.format(day),
        visible=day < 1
      )
    )
    data.append(plotly.graph_objs.Histogram(
        x=np.random.randn(500) + day,
        histnorm='count',
        name='Day {}, experimental'.format(day),
        visible=day < 1
      )
    )

steps = list()
for i in range(total_days):
    step = dict(
        method='restyle',
        args=['visible', [False] * total_days * 2],
        label='Day {}'.format(i)
    )
    step['args'][1][i * 2] = True
    step['args'][1][i * 2 + 1] = True
    steps.append(step)

sliders = [dict(
    active=0,
    steps=steps
)]

layout = dict(sliders=sliders)
fig = dict(data=data, layout=layout)
plotly.offline.iplot(fig)