简体   繁体   中英

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.

在此处输入图片说明

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

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)

在此处输入图片说明


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM