0

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

1 Answer 1

2

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"
)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.