2015-12-15 31 views
5

使用this example from plotly我試圖繪製兩條垂直線來表示平均值和中值。如何在R中繪製geom_vline中的標籤?

重現代碼

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() 

問題

我想抑制被旁邊的紅色文字顯示的 '平均' 的y值-2.2。不過,我希望文字「平均」顯示爲與下面屏幕截圖中的相同。即我只想壓制我穿過黑色十字的標籤。 同樣的問題適用於中線。

How to hide the -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

How to hide the 0?

回答

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", 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

解釋器

對象pplotly選項的列表,但不包括所有選項。它看起來R API到plotly含蓄地使用所有默認值。因此,如果您需要不同的東西,您需要將選項名稱(例如hoverinfo)附加到自定義設置(例如"name+x")。

Plotly reference material