I'm using Plotly to create a scatter plot with error bars in Python. But, I'm unable to apply a color code to error bars. In the Plotly documentation , error bar color will take only a 'single color', and thus it fails when I add color list. How could I workaround this?
I've provided a sample code, and the plot I get. If I remove the # in the color command in error dict, the code will error out.
import numpy as np
import plotly.graph_objects as go
x_data = ['10 days', '20 days', '30 days']
y_data = [0.5, 0.8, 0.4]
err_y_data = [0.1, 0.2, 0.05]
colors = ['rgba(93, 164, 214, 0.7)', 'rgba(255, 144, 14, 0.7)', 'rgba(44, 160, 101, 0.7)']
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x_data,
y=y_data,
text=np.round(y_data, 1),
mode='markers+text',
textposition='top center',
error_y=dict(
type='data',
#color = colors,
array=err_y_data,
visible=True),
marker=dict(color=colors, size=12)
))
fig.show()
I get the following plot,
However, I'll ideally want the error bars to be the same color as the respective markers. I cannot use plotly express, as I'll have to create subplots, and need control.
This is no problem at all as long as you've got your y_error data available like you do here err_y_data = [0.1, 0.2, 0.05]
. You can't add several colors to the error bars of one trace, but you can add one trace per error bar, using, among other things:
for i, bar in enumerate(err_y_data):
fig.add_trace(go.Scatter(
x=[x_data[i]],
y=[y_data[i]],
error_y=dict( type='data',color = colors[i],array=[bar],visible=True),
marker=dict(color='rgba(0,0,0,0)', size=12),
showlegend=False
))
import numpy as np
import plotly.graph_objects as go
x_data = ['10 days', '20 days', '30 days']
y_data = [0.5, 0.8, 0.4]
err_y_data = [0.1, 0.2, 0.05]
colors = ['rgba(93, 164, 214, 0.7)', 'rgba(255, 144, 14, 0.7)', 'rgba(44, 160, 101, 0.7)']
fig = go.Figure()
fig.add_trace(go.Scatter(x=x_data, y=y_data,
text=np.round(y_data, 1),
mode='markers+text',
textposition='top center',
# error_y=dict(
# type='data',
# #color = colors,
# array=err_y_data,
# visible=True),
marker=dict(color=colors, size=12),
showlegend=False
))
for i, bar in enumerate(err_y_data):
fig.add_trace(go.Scatter(
x=[x_data[i]],
y=[y_data[i]],
# text=np.round(y_data, 1),
mode='markers+text',
textposition='top center',
error_y=dict(
type='data',
color = colors[i],
array=[bar],
visible=True),
marker=dict(color='rgba(0,0,0,0)', size=12),
showlegend=False
))
fig.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.