如何删除/更改R中的图形geom_vline中的标签?

Luk*_*ham 5 plot r ggplot2 plotly

从图中使用这个例子我试图绘制两条垂直线来表示平均值和中位数.

可重复的代码

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()
Run Code Online (Sandbox Code Playgroud)

问题

我想要抑制红色文本'average'旁边显示的y值-2.2.但是,我希望文本"平均"显示在下面的屏幕截图中.即我只想压制我已经穿过黑色十字架的标签.同样的问题适用于中线.

如何隐藏-2.2?

我的非工作尝试

#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)
Run Code Online (Sandbox Code Playgroud)

此尝试仍显示0(下面的屏幕截图):

怎么隐藏0?

Luk*_*ham 3

解决方案

#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)
Run Code Online (Sandbox Code Playgroud)

结果(截图)

绘图悬停解决方案

解说员

该对象p是选项列表plotly,但不包括所有选项。看来RAPIplotly 隐式使用了所有默认值。因此,如果您想要不同的东西,您需要附加选项名称(例如hoverinfo)和自定义设置(例如"name+x")。

情节参考资料