1

I try to combine a horizontal bar chart with a vertical line across the whole plot area using plotly. But i cant figure out, how to extend the line from bottom to top.

I know how to do it with ggplot, but I explicitely want to do it with plotyl and without ggplot-conversion.

There are a couple of solutions with plotly on stackoverflow and other pages, but all solutions I found are dealing with two continuos axis.

Here is an example code I have so far:

library(plotly)
library(tidyverse)

df <- tribble(
  ~region , ~status ,
  'Reg 1' , 10000 ,
  'Reg 2' , 20000 ,
  'Reg 3' , 15000
)

target <- 17000

plot_ly(df , orientation = 'h') %>%
  add_bars(x =  ~status , y = ~region ,
           text = ~status , textposition = 'inside') %>%
  add_trace(x = target , y = ~region ,
            type = 'scatter' , mode = 'lines' ,
            line = list(color = 'darkred')) %>%
  layout(showlegend = FALSE ,
         annotations = list(text = paste('Target:\n' , target) ,
                            xref = 'x' , yref = 'paper' ,
                            x = target , y = 0.90 ,
                            xanchor = 'left' , yanchor = 'top' ,
                            showarrow = FALSE ,
                            font = list(color = 'darkred')))

I hope, someone can give me a hint, how to extend the red line from bottom to the top.

bthebread
  • 253
  • 1
  • 8

1 Answers1

1

Adapting this answer one option to achieve your desired result would be to be to switch to a continuous scale by converting your y variable to a numeric and setting the axis labels via layout. Additionally I used the range argument to fix the range of the y axis:

library(plotly)
library(tidyverse)

df <- tribble(
  ~region , ~status ,
  'Reg 1' , 10000 ,
  'Reg 2' , 20000 ,
  'Reg 3' , 15000
)

target <- 17000

plot_ly(df , orientation = 'h') %>%
  add_bars(x =  ~status , y = ~as.numeric(factor(region)),
           text = ~status , textposition = 'inside') %>%
  add_trace(x = target , y = c(.5, 3.5),
            type = 'scatter' , mode = 'lines' ,
            line = list(color = 'darkred')) %>%
  layout(showlegend = FALSE ,
         yaxis = list(
           ticktext = df$region,
           tickvals = seq_along(df$region),
           tickmode = "array",
           range = c(0.5, 3.5)
         ),
         annotations = list(text = paste('Target:\n' , target) ,
                            xref = 'x' , yref = 'paper' ,
                            x = target , y = 0.90 ,
                            xanchor = 'left' , yanchor = 'top' ,
                            showarrow = FALSE ,
                            font = list(color = 'darkred')))

stefan
  • 90,330
  • 6
  • 25
  • 51