Is there a similar way to do this in Dash?
I couldn’t find any examples.
Is there a similar way to do this in Dash?
I couldn’t find any examples.
@Bright - Yes, all examples in those docs can be used with Dash. Just set dcc.Graph(id='graph', figure=fig)
, where fig
is what’s defined in those docs.
For example:
import plotly.graph_objs as go
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_rev = x[::-1]
# Line 1
y1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1_upper = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
y1_lower = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y1_lower = y1_lower[::-1]
# Line 2
y2 = [5, 2.5, 5, 7.5, 5, 2.5, 7.5, 4.5, 5.5, 5]
y2_upper = [5.5, 3, 5.5, 8, 6, 3, 8, 5, 6, 5.5]
y2_lower = [4.5, 2, 4.4, 7, 4, 2, 7, 4, 5, 4.75]
y2_lower = y2_lower[::-1]
# Line 3
y3 = [10, 8, 6, 4, 2, 0, 2, 4, 2, 0]
y3_upper = [11, 9, 7, 5, 3, 1, 3, 5, 3, 1]
y3_lower = [9, 7, 5, 3, 1, -.5, 1, 3, 1, -1]
y3_lower = y3_lower[::-1]
trace1 = go.Scatter(
x=x+x_rev,
y=y1_upper+y1_lower,
fill='tozerox',
fillcolor='rgba(0,100,80,0.2)',
line=dict(color='rgba(255,255,255,0)'),
showlegend=False,
name='Fair',
)
trace2 = go.Scatter(
x=x+x_rev,
y=y2_upper+y2_lower,
fill='tozerox',
fillcolor='rgba(0,176,246,0.2)',
line=dict(color='rgba(255,255,255,0)'),
name='Premium',
showlegend=False,
)
trace3 = go.Scatter(
x=x+x_rev,
y=y3_upper+y3_lower,
fill='tozerox',
fillcolor='rgba(231,107,243,0.2)',
line=dict(color='rgba(255,255,255,0)'),
showlegend=False,
name='Fair',
)
trace4 = go.Scatter(
x=x,
y=y1,
line=dict(color='rgb(0,100,80)'),
mode='lines',
name='Fair',
)
trace5 = go.Scatter(
x=x,
y=y2,
line=dict(color='rgb(0,176,246)'),
mode='lines',
name='Premium',
)
trace6 = go.Scatter(
x=x,
y=y3,
line=dict(color='rgb(231,107,243)'),
mode='lines',
name='Ideal',
)
data = [trace1, trace2, trace3, trace4, trace5, trace6]
layout = go.Layout(
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='rgb(229,229,229)',
xaxis=dict(
gridcolor='rgb(255,255,255)',
range=[1,10],
showgrid=True,
showline=False,
showticklabels=True,
tickcolor='rgb(127,127,127)',
ticks='outside',
zeroline=False
),
yaxis=dict(
gridcolor='rgb(255,255,255)',
showgrid=True,
showline=False,
showticklabels=True,
tickcolor='rgb(127,127,127)',
ticks='outside',
zeroline=False
),
)
fig = go.Figure(data=data, layout=layout)
app.layout = html.Div([
dcc.Graph(id='error-bars', figure=fig)
])
I created a method that handles a dataframe the same way as seaborn does it. See link below.
Someone may find this useful. I wrote a simple function to extend plotly.express.line
using the same interface as plotly.express.scatter
:
def line(error_y_mode=None, **kwargs):
"""Extension of `plotly.express.line` to use error bands."""
ERROR_MODES = {'bar','band','bars','bands',None}
if error_y_mode not in ERROR_MODES:
raise ValueError(f"'error_y_mode' must be one of {ERROR_MODES}, received {repr(error_y_mode)}.")
if error_y_mode in {'bar','bars',None}:
fig = px.line(**kwargs)
elif error_y_mode in {'band','bands'}:
if 'error_y' not in kwargs:
raise ValueError(f"If you provide argument 'error_y_mode' you must also provide 'error_y'.")
figure_with_error_bars = px.line(**kwargs)
fig = px.line(**{arg: val for arg,val in kwargs.items() if arg != 'error_y'})
for data in figure_with_error_bars.data:
x = list(data['x'])
y_upper = list(data['y'] + data['error_y']['array'])
y_lower = list(data['y'] - data['error_y']['array'] if data['error_y']['arrayminus'] is None else data['y'] - data['error_y']['arrayminus'])
color = f"rgba({tuple(int(data['line']['color'].lstrip('#')[i:i+2], 16) for i in (0, 2, 4))},.3)".replace('((','(').replace('),',',').replace(' ','')
fig.add_trace(
go.Scatter(
x = x+x[::-1],
y = y_upper+y_lower[::-1],
fill = 'toself',
fillcolor = color,
line = dict(
color = 'rgba(255,255,255,0)'
),
hoverinfo = "skip",
showlegend = False,
legendgroup = data['legendgroup'],
)
)
# Reorder data as said here: https://stackoverflow.com/a/66854398/8849755
reordered_data = []
for i in range(int(len(fig.data)/2)):
reordered_data.append(fig.data[i+int(len(fig.data)/2)])
reordered_data.append(fig.data[i])
fig.data = tuple(reordered_data)
return fig
Usage example:
import plotly.express as px
import pandas
df = px.data.gapminder().query('continent=="Americas"')
df = df[df['country'].isin({'Argentina','Brazil','Colombia'})]
df['lifeExp std'] = df['lifeExp']*.1 # Invent some error data...
for error_y_mode in {'band', 'bar'}:
fig = line(
data_frame = df,
x = 'year',
y = 'lifeExp',
error_y = 'lifeExp std',
error_y_mode = error_y_mode,
color = 'country',
title = f'Using error {error_y_mode}',
markers = '.',
)
fig.show()
Result:
Steps are given below-
Click anywhere in the chart.
Click the Chart Elements button Chart Elements button next to the chart, and then check the Error Bars box. (Clear the box to remove error bars.)
To change the error amount shown, click the arrow next to Error Bars, and then pick an option.
Pick a predefined error bar option like Standard Error, Percentage or Standard Deviation.
Pick More Options to set your own error bar amounts, and then under Vertical Error Bar or Horizontal Error Bar, choose the options you want. This is also where you can change the direction, end style of the error bars, or create custom error bars.
Regards,
Rachel Gomez