Search code examples
rggplot2plotlyggplotly

ggplotly - adjusting error bar width and thickness


I'm creating a barplot with error bars using ggplotly. The transition into plotly changes the width and thickness of the error bars, and I would like to format them to my preference. I saw that I'm supposed to do that using the style function, but can't quite figure it out. I can see that the trace I need is called error_y and I can change the attributes of the bars, but can't figure out how to change any attribute of the error bars...

library(dplyr)
library(ggplot2)
library(plotly)

df <- data.frame(y = c(5, 10), group = c("a", "b"))
p <- ggplot(df) +
        geom_bar(aes(x = group, y = y), stat = "identity") +
        geom_errorbar(aes(x = group, ymin = y - 1, ymax = y + 1), linewidth = 0.1, width = 0.7) 
        
ggp <- ggplotly(p)
str(ggp) # I can see the markers (the bars) and the error_y (the error bars in the structure of the plotly object

# can modify attributes of the bars successfully
style(ggp, traces = 1, marker = list(color = "red"))
# fail to modify attributes of the errorbars
style(ggp, error_y = list(thickness = 2.5))

Solution

  • It is not very intuitive, but you need to set error_y.VARIABLE to your desired value.

    library(ggplot2)
    library(plotly)
    
    df <- data.frame(y = c(5, 10), group = c("a", "b"))
    
    p <- ggplot(df) +
      geom_bar(aes(x = group, y = y), stat = "identity") +
      geom_errorbar(aes(x = group, ymin = y - 1, ymax = y + 1), 
                    linewidth = 0.1, width = 0.7) 
    
    ggp <- ggplotly(p)
    
    ## Original plot
    ggp
    ## Updated with style()
    style(ggp,  error_y.thickness = 5, error_y.color = "red", error_y.width = 40)
    

    Original plot:

    Updated with style():

    Looking at plotly structure could be useful in these cases:

    require(listviewer)
    plotly_json(ggp)