Search code examples
rplotlyr-plotly

R plotly bar plot with additional line doesn't work


please, I have the following bar plot and I'm trying to display the average line on top of the bar plot but somehow my code below doesn't work, it shows only the line as soon as I add it to fig. My first step is creating the bar plot:

vect_x = c("A",   "AA" , "AAA", "A"  , "AA",  "AAA")
vect_y <- c(137.2, 306.2,  76.2 , 73.2, 220.9 , 99.3)
vect_group <- c("US","US","US","Europe","Europe","Europe")
fig <- plot_ly(x = ~vect_x, y = ~vect_y, color = ~vect_group)

This works perfectly. At this point, I would like to plot a horizontal line showing the average value. I read plotly bar and line chart and Adding a horizontal line to a plotly bar graph but none of the solutions suggested seem to work. As soon as I add the following code, the plot display just a line:

avg_value <- mean(vect_y, na.rm = T)
fig %>% add_trace(,
                             x = ~vect_x,
                             y = ~rep(avg_value, length(vect_y)),
                             type='scatter',
                             mode='lines+markers',
                             line = list(color = 'black')
                          )

Does anybody know what I'm doing wrong? Many thanks


Solution

  • One option to achieve your desired result would be to add the bars as a separate layer via add_trace or add_bars:

    library(plotly)
    
    vect_x <- c("A", "AA", "AAA", "A", "AA", "AAA")
    vect_y <- c(137.2, 306.2, 76.2, 73.2, 220.9, 99.3)
    vect_group <- c("US", "US", "US", "Europe", "Europe", "Europe")
    
    fig <- plot_ly() %>% 
      add_trace(x = ~vect_x, y = ~vect_y, color = ~vect_group, type = 'bar')
    
    avg_value <- mean(vect_y, na.rm = T)
    fig %>% add_trace(
      x = ~vect_x,
      y = ~rep(avg_value, length(vect_y)),
      type = "scatter",
      mode = "lines+markers",
      line = list(color = "black"),
      marker = list(color = "black"),
      name = "mean"
    )