pssguy
pssguy

Reputation: 3505

How can I add a vertical line to a plotly chart in R with the y variable a factor

I have a data.frame where I plot a value,id, on the y axis against a value t on the x axis ordered by another value s

library(plotly)
library(dplyr)

# create data.frame
df <- data.frame(id=c("a","b","c"),s=c(1,3,2),t=c(3,2,1))

# set order
levels <- df %>% 
arrange(s) %>% 
.$id #[1] a c b

# plot
df %>% 
mutate(id=factor(id, levels = levels)) %>%
plot_ly(x=~t,y=~id) %>% 
add_markers() 

This works fine.

enter image description here

However I want to add a vertical line indicating the average of t, weighted by s

line <- weighted.mean(df$t,df$s)

and I am unable to find the correct way to do it

TIA

Upvotes: 1

Views: 4841

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31649

In order to prevent Plotly to sort the y-axis with the categorical values you could draw multiple lines which appear as one.

p <- add_lines(p, 
               x = rep(line, nrow(df)), 
               y = df$id)

enter image description here


library(plotly)
library(dplyr)

# create data.frame
df <- data.frame(id=c("a","b","c"),s=c(1,3,2),t=c(3,2,1))

# set order
levels <- df %>% 
  arrange(s) %>% 
  .$id #[1] a c b

# plot
p <- df %>% 
  mutate(id=factor(id, levels = levels)) %>%
  plot_ly(x=~t,y=~id) %>% 
  add_markers()

line <- weighted.mean(df$t,df$s)


p <- add_lines(p, 
               x = rep(line, nrow(df)), 
               y = df$id)
p

Upvotes: 2

Related Questions