如何在R中移除/更改plotly geom_vline的标签?

5

我正在尝试使用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()

问题

我想要隐藏显示在红色文本“average”旁边的y值-2.2。但是,我希望文本“average”像下面截图中一样显示。也就是说,我只想要隐藏我用黑色叉号标记的标签。 同样的问题也适用于中位数线。

如何隐藏-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)

这次尝试仍然显示为0(如下图所示):

如何隐藏0?

1个回答

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)

结果(截图)

plotlyHoverSolution

说明

对象p是一个包含plotly选项的列表,但并不包括所有选项。看起来plotlyR API会隐式使用所有默认值。因此,如果您想要不同的内容,需要将选项名称(例如hoverinfo)附加上自定义设置(例如"name+x")。

Plotly参考材料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接