2017-02-25 33 views
1

假設我做小提琴的情節,有說10個小提琴,使用下面的代碼:小提琴地塊與附加分

library(ggplot2)  
library(reshape2) 

df <- melt(data.frame(matrix(rnorm(500),ncol=10))) 
p <- ggplot(df, aes(x = variable, y = value)) + 
     geom_violin() 
p 

如下,我可以添加表示每個變量的均值點:

p + stat_summary(fun.y=mean, geom="point", size=2, color="red") 

我該如何做一些類似的事情,但對於任意點?
例如,如果我產生10個新的點,從每個分佈中抽取的,我怎麼可能畫出那些作爲小提琴點?

回答

2

你可以給任何功能,stat_summary提供它只是返回一個值。所以人們可以使用功能sample。把額外的參數,如size,在fun.args

p + stat_summary(fun.y = "sample", geom = "point", fun.args = list(size = 1)) 
1

假設你點都使用相同的組名(即variable)資格,你應該能夠與手動定義它們:

newdf <- group_by(df, variable) %>% sample_n(10) 
p + geom_point(data=newdf) 

這些點可以是任何東西,包括靜態數字:

newdf <- data.frame(variable = unique(df$variable), value = seq(-2, 2, len=10)) 
p + geom_point(data=newdf) 
0

我有類似的問題。下面的代碼舉例說明了玩具問題 - 如何爲小提琴劇情添加任意點? - 和解決方案。

## Visualize data set that comes in base R 

head(ToothGrowth) 

## Make a violin plot with dose variable on x-axis, len variable on y-axis 

# Convert dose variable to factor - Important! 
ToothGrowth$dose <- as.factor(ToothGrowth$dose) 

# Plot 
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + 
      geom_violin(trim = FALSE) + 
      geom_boxplot(width=0.1) 

# Suppose you want to add 3 blue points 
# [0.5, 10], [1,20], [2, 30] to the plot. 
# Make a new data frame with these points 
# and add them to the plot with geom_point(). 

TrueVals <- ToothGrowth[1:3,] 
TrueVals$len <- c(10,20,30) 

# Make dose variable a factor - Important for positioning points correctly! 
TrueVals$dose <- as.factor(c(0.5, 1, 2)) 

# Plot with 3 added blue points 

p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + 
      geom_violin(trim = FALSE) + 
      geom_boxplot(width=0.1) + 
      geom_point(data = TrueVals, color = "blue")