Reputation: 3505
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
Upvotes: 1
Views: 4841
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)
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