我正在使用Dash图形对象,但我对此很陌生。我试图传递一个在同一图形上具有2个散点图和一个条形图的图形,但是我希望条形图(绿色)位于它自己的辅助y轴上,因此它看起来比这里要好:
现在,根据我对Dash的了解,我必须传递一个go.Figure()
对象,所以我有一个定义data
和layout
的函数。我在plotly文档中看到可以使用plotly express add辅助轴,但是我不确定如何在此处的框架内完成该操作。任何帮助将不胜感激!
这是我的代码:
def update_running_graph(n_intervals):
df = pd.read_csv(filename)
trace1 = go.Scatter(x=df['Timestamp'],
y=df['CLE'],
name='Crude',
mode='lines+markers')
trace2 = go.Scatter(x=df['Timestamp'],
y=df['y_pred'],
name='Model',
mode='lines+markers')
trace3 = go.Bar(x=df['Timestamp'],
y=df['ModelDiff'],
name='Diff',
)
data = [trace1, trace2,trace3]
layout = go.Layout(title='CLE vs Model')
return go.Figure(data=data, layout=layout)
答案 0 :(得分:8)
要以虚线添加辅助y轴,您可以执行以下操作:
def update_running_graph(n_intervals):
df = pd.read_csv(filename)
trace1 = go.Scatter(x=df['Timestamp'],
y=df['CLE'],
name='Crude',
mode='lines+markers',
yaxis='y1')
trace2 = go.Scatter(x=df['Timestamp'],
y=df['y_pred'],
name='Model',
mode='lines+markers',
yaxis='y1')
trace3 = go.Bar(x=df['Timestamp'],
y=df['ModelDiff'],
name='Diff',
yaxis='y2'
)
data = [trace1, trace2,trace3]
layout = go.Layout(title='CLE vs Model',
yaxis=dict(title='Crude and Model'),
yaxis2=dict(title='Moddel Difference',
overlaying='y',
side='right'))
return go.Figure(data=data, layout=layout)
您可以添加更多的y轴,它们始终需要以yi
的形式带有第i个i轴。然后,在布局中,您可以使用yaxisi=dict(...)
指定第i轴的布局。
答案 1 :(得分:0)
此documentation page应该有用。只需修改以适合您的代码,因为trace1和trace2似乎在相同的比例上,只需将trace3设置为辅助轴比例,就应该设置了。下面是一个仅包含2个示例的示例,但是添加第三个示例应该不太困难。
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
fig.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
fig.update_xaxes(title_text="xaxis title")
# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
fig.show()
干杯!