I have generated the following plot, which groups the data based on drug. I then created another data frame which summarized the main data by calculating the mean. These mean values(grouped by drug) are then added to the plot in triangular shapes. Using stat_summary connected the means. Now I would like to know how to add the tooltips for the means data (including x and y values with custom labels) to the plot using ggplotly. The current tooltip only includes the info for the main data
data:
Day,Drug,Sex,Y
1,A,Female,2.192306074
1,B,Male,4.551912798
1,B,Female,1.574070652
1,C,Female,-0.143946163
1,A,Male,5.144422967
1,C,Male,5.724705829
2,A,Male,2.691617258
2,B,Female,-3.0289955
2,C,Male,0.338102762
2,A,Female,-0.558581233
2,B,Female,-2.942620032
2,C,Male,1.024670497
3,A,Male,2.264980803
3,C,Female,2.103722883
3,A,Female,2.091621938
3,B,Male,1.535299922
3,B,Male,1.618399767
3,C,Female,0.136160703
After copying you may need to run the following command to convert it to the dataframe:
df <- read.delim("clipboard", sep = ",")
my variables are in string:
grouping_var <- "Drug"
x <- "Day"
y <- "Y"
color <- "Sex"
Here is the code for that the plot:
text <- paste("X:", df[[grouping_var]], "<br>",
"Y:", df[[y]], "<br>",
"group:", grouping_var, "<br>",
"color:", color)
mean_df <- df %>% group_by(get(x), get(grouping_var)) %>% summarise(Mean = mean(get(y)), .groups = "drop") %>%
rename(x = 1, grouping_var = 2)
p <- df %>% ggplot(aes(x = get(x), y = get(y), text = text)) +
geom_point(aes_string(group = grouping_var, color = color)) +
stat_summary(fun=mean, geom="line", aes_string(group = grouping_var), color = "red", lty = 2) +
geom_point(data = mean_df, aes(x = x, y = Mean, group = grouping_var, color = grouping_var),
pch = 2, size = 3,inherit.aes = F) +
xlab(x)+
ylab(y)
ggplotly(p, tooltip = c("text"))

