dan
dan

Reputation: 6314

Adding error bars to a grouped R plotly bar chart

I have data I'd like to plot using an R plotly bar graph with y error bars. The data consist of two groups, each with measurements from three types:

set.seed(1)
df <- data.frame(group = c(rep("A",3),rep("B",3)),
                 type = rep(letters[1:3],2),
                 mean.proportion = runif(6,0,1),
                 se.proportion = runif(6,0.01),
                 stringsAsFactors = F)
df$group <- factor(df$group)
df$type <- factor(df$type)

If I only plot the bars with no error bars using:

plotly::plot_ly(x=df$type,y=df$mean.proportion,type='bar',color=df$group,showlegend=T) %>%
  plotly::layout(xaxis=list(title=NA),yaxis=list(title="Proportion"),barmode='group')

It comes out fine:

enter image description here

However, when I try to add y error bars using:

plotly::plot_ly(x=df$type,y=df$mean.proportion,type='bar',color=df$group,showlegend=T) %>%
  plotly::layout(xaxis=list(title=NA),yaxis=list(title="Proportion"),barmode='group') %>%
  plotly::add_trace(error_y=list(array=df$se.proportion))

It gets messed up - the bras get doubled: enter image description here

Any idea?

Upvotes: 0

Views: 1351

Answers (1)

arg0naut91
arg0naut91

Reputation: 14764

Try plotting them within the first statement:

plotly::plot_ly(x=df$type,y=df$mean.proportion,type='bar',color=df$group,showlegend=T, error_y=list(array=df$se.proportion)) %>%
  plotly::layout(xaxis=list(title=NA),yaxis=list(title="Proportion"),barmode='group')

Output:

enter image description here

Upvotes: 1

Related Questions