0

Basically, I have this dataframe:

# dataframe
df2 = data.frame(value = c(9, 2, 7, 5, 6),
                 key = c('ar', 'or', 'br', 'gt', 'ko'))

And this is the plot I need. I'm using reorder, because I know it is a good way to order the bars correctly.

library(tidyverse)
df2 %>% ggplot() + 
  geom_col(aes(reorder(key, -value), value), fill = 'grey') + 
  geom_hline(yintercept = 4)

CORRECT PLOT


I'm trying to do this in plotly, but everytime I use reorder, it doesn't work properly.

Also, I would like the segment to start in the extreme left side of the first bar and end in the extreme right side of the last bar.

# using reorder to order the bars doesn't work!
df2 %>% 
  plot_ly(x = ~reorder(key, -value), # <- here
          y = ~value,
          color = I('grey'),
          type = 'bar') %>% 
  add_segments(x = 'ar', xend = 'or',
               y = 4, yend = 4, 
               color = I('black'))

WRONG PLOT

Any tips here?

stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

0

The issue is that adding the segments breaks the order of your bars. However, adapting this post to your example you could achieve your desired result by manually setting the order of the x axis via layout:

library(plotly)

xform <- list(categoryorder = "array",
              categoryarray = levels(reorder(df2$key, -df2$value)))

df2 %>% 
  plot_ly(x = ~key,
          y = ~value,
          color = I('grey'),
          type = 'bar') %>% 
  add_segments(x = 'ar', xend = 'or',
               y = 4, yend = 4, 
               color = I('black')) %>%
  layout(xaxis = xform)

To fix your second issue: Adapting this post you could switch to a continuous scale by converting your key variable to a numeric and setting the axis labels via layout:

df2 %>%
  plot_ly(
    x = ~ as.numeric(reorder(key, -value)),
    y = ~value,
    color = I("grey"),
    type = "bar"
  ) %>%
  add_segments(
    x = .6, xend = 5.4,
    y = 4, yend = 4,
    color = I("black")
  ) %>%
  layout(
    xaxis = list(
      ticktext = levels(reorder(df2$key, -df2$value)),
      tickvals = seq_along(df2$key),
      tickmode = "array",
      range = c(0.5, 5.5)
    )
  )

stefan
  • 90,330
  • 6
  • 25
  • 51