您好,有人可以提供一个代码示例,说明如何在Dash中创建带有均线的条形图。
我设法创建了一个条形图,但是我无法找到如何通过回调函数输出向现有的dcc.Graph添加跟踪。
非常感谢您。
这是图表外观的一个示例:
以下是我尝试过的一些代码片段:
html.Div([
dcc.Graph(id='surprice_pct_last_month1'),
],style={'width': '48%', 'display': 'inline-block'}),
和
@app.callback(
dash.dependencies.Output('surprice_pct_last_month2', 'figure'),
[dash.dependencies.Input('currency2', 'value')])
def update_surprise_last_month2(currency2):
output = calendar[calendar.Currency == currency2]
output = output.groupby('Event').last()
output = output.dropna()
output1 = output[(output.Surprise_Pct < 400) & (output.Surprise_Pct > -400)]
output2 = output[(output.Surprise_Pct > 399) | (output.Surprise_Pct < -399)]
output['Mean'] = output.Surprise_Pct.mean()
output['Median'] = output.Surprise_Pct.median()
#output2['Mean'] = output2.Surprise_Pct.mean()
#output2['Median'] = output2.Surprise_Pct.median()
data = []
trace_data = go.Bar(x=list(output.index),
y=list(output.Surprise_Pct))
data.append(trace_data)
layout = {'title':'Monthly Surprises - {}'.format(currency2)}
return {
'data':data,
'layout': layout
}
答案 0 :(得分:0)
这是您需要的吗?
import plotly.graph_objects as go
import random
y = [random.randrange(-200,200) for _ in range(80)]
mean = sum(y) / len(y)
fig = go.Figure([go.Bar(x=list(range(len(y))), y=y)])
fig.add_shape(
go.layout.Shape(
type="line",
x0=-.5,
y0=mean,
x1=len(y)-.5,
y1=mean,
line=dict(
color="Orange",
width=4,
dash="dash",
),
))
fig.show()
PS:This online example建议数据只是字典列表。因此,为了使Dash正常工作,我建议:
tracedata1 = go.Bar(x=x, y=y)
tracedata2 = go.layout.Shape(type="line", ...)
data.append(trace_data1)
data.append(trace_data2)
答案 1 :(得分:0)
根据JohanC的建议,我弄清楚了如何利用Dash和Plotly。 我没有意识到,可以简单地将另一个字典添加到数据列表中,然后在字典中指定将数据显示为哪种图形类型。
@app.callback(
dash.dependencies.Output('surprice_pct_last_month1', 'figure'),
[dash.dependencies.Input('currency1', 'value')])
def update_surprise_last_month1(currency1):
output = calendar[calendar.Currency == currency1]
output = output.groupby('Event').last()
output = output.dropna()
output1 = output[(output.Surprise_Pct < 400) & (output.Surprise_Pct > -400)]
output2 = output[(output.Surprise_Pct > 399) | (output.Surprise_Pct < -399)]
output['Mean'] = output.Surprise_Pct.mean()
output['Median'] = output.Surprise_Pct.median()
#output2['Mean'] = output2.Surprise_Pct.mean()
#output2['Median'] = output2.Surprise_Pct.median()
data = []
trace_data = go.Bar(x=list(output.index), y=list(output.Surprise_Pct), name='Surprise in %')
trace_data2 = {'x': output.index, 'y': output.Median, 'type': 'scatter', 'name': 'Median'}
trace_data3 = {'x': output.index, 'y': output.Mean, 'type': 'scatter', 'name': 'Mean'}
print(output.Median)
print(output.Mean)
data.append(trace_data)
data.append(trace_data2)
data.append(trace_data3)
layout = {'title':'Monthly Surprises - {}'.format(currency1)}
return {
'data':data,
'layout': layout
}