Using this example from plotly I am attempting to plot two vertical lines to represent the mean and median.
Reproducible Code
library(plotly)
# data
df1 <- data.frame(cond = factor( rep(c("A","B"), each=200) ),
rating = c(rnorm(200),rnorm(200, mean=.8)))
df2 <- data.frame(x=c(.5,1),cond=factor(c("A","B")))
# graph
ggplot(data=df1, aes(x=rating, fill=cond)) +
geom_vline(aes(xintercept=mean(rating, na.rm=T))
, color="red", linetype="dashed", size=1, name="average") +
geom_vline(aes(xintercept=median(rating, na.rm=T))
, color="blue", linetype="dashed", size=1, name="median") +
geom_histogram(binwidth=.5, position="dodge")
ggplotly()
Problem
I want to suppress the y-value -2.2 that is displayed next to the red text 'average'. However, I want the text 'average' to display as it does in the screenshot below. I.e. I only want to suppress the label that I have put a black cross through. The same problem applies to the median line.
My non-working attempt
#plot
gg <- ggplot(data=df1, aes(x=rating, fill=cond)) +
geom_vline(aes(xintercept=mean(rating, na.rm=T))
, color="red", linetype="dashed", size=1, name="average")+
geom_vline(aes(xintercept=median(rating, na.rm=T))
, color="blue", linetype="dashed", size=1, name="median") +
geom_histogram(binwidth=.5, position="dodge")
p <- plotly_build(gg)
# p$data[[1]]$y[1:2] <- " " # another attempt, but the line doesn't display at all
p$data[[1]]$y <- NULL # delete the y-values assigned to the average line
plotly_build(p)
This attempt still displays a 0
(screenshot below):
Solution
#plot
gg <- ggplot(data=df1, aes(x=rating, fill=cond)) +
geom_vline(aes(xintercept=mean(rating, na.rm=T))
, color="red", linetype="dashed", size=1, name="average")+
geom_vline(aes(xintercept=median(rating, na.rm=T))
, color="blue", linetype="dashed", size=1, name="median", yaxt="n") +
geom_histogram(binwidth=.5, position="dodge")
#create plotly object
p <- plotly_build(gg)
#append additional options to plot object
p$data[[1]]$hoverinfo <- "name+x" #hover options for 'average'
p$data[[2]]$hoverinfo <- "name+x" #hover options for 'median'
#display plot
plotly_build(p)
Result (screenshot)
Explainer
The object p
is a list of plotly
options, but does not include all options. It appears the R
API to plotly
implicitly uses all the defaults. Therefore, if you want something different you need to append the option name (e.g. hoverinfo
) with the custom settings (e.g. "name+x"
).
Plotly reference material
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With