Python 使用Plotly的带滑块的交互式打印

Python 使用Plotly的带滑块的交互式打印,python,plotly,Python,Plotly,如何使用Plotly在Python中重新创建以下交互式绘图 我的简单示例绘制了一个条形图,其中一列为x,另一列为1-x 来自Mathematica的GIF: 滑块允许x在0和1之间变化 Mathematica代码: Manipulate[BarChart[{x, 1 - x}, PlotRange -> {0, 1}], {{x, 0.3, "Level"}, 0, 1, Appearance -> "Open"}] 更新 以下是我不喜欢的解决方案: import p

如何使用Plotly在Python中重新创建以下交互式绘图

我的简单示例绘制了一个条形图,其中一列为x,另一列为1-x

来自Mathematica的GIF:

滑块允许x在0和1之间变化

Mathematica代码:

Manipulate[BarChart[{x, 1 - x}, PlotRange -> {0, 1}], 
    {{x, 0.3, "Level"}, 0, 1, Appearance -> "Open"}]

更新

以下是我不喜欢的解决方案:

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)

import ipywidgets as widgets
绘图:

def update_plot(x):
    data = [go.Bar(
                x=['1', '2'],
                y=[x, 1-x]
    )]
    iplot(data, show_link=False)

x = widgets.FloatSlider(min=0, max=1, value=0.3)
widgets.interactive(update_plot, x=x)
这方面的问题:

  • 移动滑块时,打印将闪烁
  • 滑块放错地方了
  • 增量不够精确
  • 我自己无法指定精确的值

下面的代码在plotlyDash中创建交互式绘图。它需要两个输入:滑块和文本框。当下面的代码保存为“
.py
”并且文件在终端中运行时,它应该在终端中运行本地服务器。接下来,从该服务器复制在http://地址上运行的
*并将其粘贴到浏览器中以打开绘图。很可能是
http://127.0.0.1:8050/
。资源:。(
Python 3.6.6

重要提示:请注意,要使滑块工作,文本框值必须重置为“
0
”(零)

导入库

import numpy as np
import pandas as pd
from plotly import __version__
import plotly.offline as pyo
import plotly.graph_objs as go

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline

import json
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
init_notebook_mode(connected=True)

init_notebook_mode(connected=True)
cf.go_offline()
traces = []
q = np.linspace(0,1, 100)
for i in range(0,len(q)):
    trace = dict(
                type = 'bar',
                visible = False,
                x=[1, 2],
                y=[q[i], 1 - q[i]],
                marker=dict(color='#ffbf00'),
                width=0.5
             )
    traces.append(trace)

traces[0]['visible'] = 'True'
创建短跑应用程序

app = dash.Dash()
app.layout = html.Div(
      html.Div([
            html.Div([html.H5("Level"),

                    dcc.Slider(id='slider_input',
                                min=0,
                                max=1,
                                step=0.005,
                                value=0.1,
                    )],style={'width': '200'}
                ),

            html.Div(style={'height': '10'}),

            html.Div(dcc.Input( id='text_input',
                        placeholder='Enter a value...',
                        type='text',
                        value=0.0
                    ),style={'width': '50'}),

            dcc.Graph(id='example',
                     figure={'data':[{'x':[1,2],
                                      'y':[0,1],
                                      'type':'bar',
                                      'marker':dict(color='#ffbf00')
                                     }],
                              'layout': go.Layout(title='Plot',
                                                  #xaxis = list(range = c(2, 5)),
                                                  yaxis=dict(range=[0, 1])
                                                   )
                               })

          ], style={'width':'500', 'height':'200','display':'inline-block'})
)

# callback - 1 (from slider)
@app.callback(Output('example', 'figure'),
             [Input('slider_input', 'value'),
             Input('text_input', 'value')])

def update_plot(slider_input, text_input):
    if (float(text_input)==0.0):
        q = float(slider_input)
    else:
        q = float(text_input)

    figure = {'data': [go.Bar(x=[1,2],
                              y=[q, 1-q],
                              marker=dict(color='#ffbf00'),
                              width=0.5
                       )],
              'layout': go.Layout(title='plot',
                                  #xaxis = list(range = c(2, 5)),
                                  yaxis=dict(range=[0, 1])
                                )
            }
    return figure
运行服务器

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

sliders = [dict(
    active = 10,
    currentvalue = {"prefix": "Level: "},
    #pad = {"t": 50},
    steps = steps

)]
输出

layout = go.Layout(
    width=500,
    height=500,
    autosize=False,
    yaxis=dict(range=[0, 1])
)

layout['sliders'] = sliders

编辑-1

仅使用滑块打印

下面的代码不带破折号地使用plotly。绘图与滑块交互。请注意,此代码没有用于更改绘图的文本输入(如上所述)。但是,下面的绘图应该使用滑块进行更新,而无需“释放”滑块即可查看更新。在此绘图中,为绘图创建了单独的记录道

导入库

import numpy as np
import pandas as pd
from plotly import __version__
import plotly.offline as pyo
import plotly.graph_objs as go

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline

import json
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
init_notebook_mode(connected=True)

init_notebook_mode(connected=True)
cf.go_offline()
traces = []
q = np.linspace(0,1, 100)
for i in range(0,len(q)):
    trace = dict(
                type = 'bar',
                visible = False,
                x=[1, 2],
                y=[q[i], 1 - q[i]],
                marker=dict(color='#ffbf00'),
                width=0.5
             )
    traces.append(trace)

traces[0]['visible'] = 'True'
创建跟踪

import numpy as np
import pandas as pd
from plotly import __version__
import plotly.offline as pyo
import plotly.graph_objs as go

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline

import json
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
init_notebook_mode(connected=True)

init_notebook_mode(connected=True)
cf.go_offline()
traces = []
q = np.linspace(0,1, 100)
for i in range(0,len(q)):
    trace = dict(
                type = 'bar',
                visible = False,
                x=[1, 2],
                y=[q[i], 1 - q[i]],
                marker=dict(color='#ffbf00'),
                width=0.5
             )
    traces.append(trace)

traces[0]['visible'] = 'True'
创建滑块

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

sliders = [dict(
    active = 10,
    currentvalue = {"prefix": "Level: "},
    #pad = {"t": 50},
    steps = steps

)]
创建布局

layout = go.Layout(
    width=500,
    height=500,
    autosize=False,
    yaxis=dict(range=[0, 1])
)

layout['sliders'] = sliders
绘图图

fig = go.Figure(data=traces, layout=layout)

#pyo.iplot(fig, show_link=False) # run this line to view inline in Jupyter Notebook
pyo.plot(fig, show_link=False) # run this line to view in browser 

从Plotly 3.0开始,可以通过以下方式实现(在JupyterLab中):

导入plotly.graph\u对象
从ipywidgets导入交互
fig=go.FigureWidget()
条形图=图添加条形图(x=['x','1-x'])
图布局=dict(yaxis=dict(范围=[0,1]),高度=600)
@交互(x=(0,1,0.01))
def更新(x=0.3):
使用图batch_update():
条形y=[x,1-x]
无花果


更新


从Plotly 4.0中,您需要指定
fig.data[0].y
,而不是
bar.y

请看一看和?如果您对一段代码有特定的问题,Stackoverflow社区将乐于提供帮助。我认为这个问题非常具体。您发送给我的文档非常糟糕。如果你选择用例子来解释某件事,至少再举几个例子。是的,从一般的观点来看,这个问题相当具体。然而,在这样的背景下,它实际上是相当广泛的。你读过维基吗?看看那里,你会发现要求解决这类问题并不是很受社区欢迎。我建议对手头的主题进行更广泛的搜索,因为这似乎是一个相当琐碎的情况,而且肯定有人在过去处理过。请具体点,你希望我写什么比这更具体?我已经阅读了指南。是的,问题是如此简单,或者至少应该如此,以至于我不需要包含任何代码。我不需要修补的解决方案,我需要一种优雅、聪明的解决方法。我认为这个问题不应该像plot.ly/python/sliders上显示的那样得到解决。如果你对此一无所知,请不要发表任何评论。请不要把自己和整个社区联系在一起。那里也有乐于助人和聪明的人。很好!您知道如何使其具有同步更新(即在移动滑块时更改图表)吗?我在文档中查找了
dash
,似乎必须释放
滑块才能看到效果。(). 我仅使用plotly在Edit-1中添加了另一个代码。此图中的滑块响应更快。请注意,此绘图没有用于更新绘图的文本输入。