以下代码创建了一个交互式图表,使用了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',
yaxis=dict(range=[0, 1])
)
})
], style={'width':'500', 'height':'200','display':'inline-block'})
)
@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',
yaxis=dict(range=[0, 1])
)
}
return figure
运行服务器
if __name__ == '__main__':
app.run_server()
输出
编辑 - 1 .............................
只用滑块绘制图形
以下代码使用不带dash的plotly。该图形是交互式的,带有一个滑块。请注意,此代码没有文本输入以更改图形(如上所述)。但是,下面的图应该会在滑块更新而无需“释放”滑块即可查看更新。在这个图中,为绘制创建了单个跟踪。
导入库
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
steps.append(step)
sliders = [dict(
active = 10,
currentvalue = {"prefix": "Level: "},
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.plot(fig, show_link=False)