如何使用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)
存在此问题
答案 0 :(得分:2)
下面的代码在plotly
和Dash
中创建一个交互式绘图。它需要两个输入:滑块和文本框。当以下代码另存为'.py
'并且文件在终端中运行时,它应在终端中运行本地服务器。接下来,从该服务器复制* Running on http://
地址并将其粘贴到浏览器中以打开绘图。最有可能是http://127.0.0.1:8050/
。资源:1,2,3。 (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
创建Dash应用
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()
输出
编辑-1 ......................................
仅具有滑块的图
下面的代码使用了不带破折号的绘图。该图与滑块互动。请注意,此代码没有用于更改绘图的文本输入(如上所述)。但是,下图应使用滑块进行更新,而无需“释放”滑块以查看更新。在此绘图中,创建了单独的迹线以进行绘图。
导入库
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'
创建滑块
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
答案 1 :(得分:0)
从Plotly 3.0开始,可以通过以下方式实现(在JupyterLab中):
import plotly.graph_objs as go
from ipywidgets import interact
(对于Jupyter笔记本,我认为您仍然需要from plotly.offline import init_notebook_mode, iplot
和
init_notebook_mode(connected=True)
)
fig = go.FigureWidget()
bar = fig.add_bar(x=['x', '1-x'])
fig.layout = dict(yaxis=dict(range=[0,1]), height=600)
@interact(x=(0, 1, 0.01))
def update(x=0.3):
with fig.batch_update():
bar.y=[x, 1-x]
fig