假设我用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个新点,从每个分布中抽取一个,我怎样才能将它们绘制为小提琴上的点?
答案 0 :(得分:2)
如果只返回一个值,您可以向stat_summary
提供任何功能。所以可以使用函数sample
。在size
fun.args
等额外参数
p + stat_summary(fun.y = "sample", geom = "point", fun.args = list(size = 1))
答案 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)
答案 2 :(得分: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")