ggplot2: geom_violin(), geom_text() 和 facet_grid() 打印每个因子的总行数,不包括 NA
ggplot2: geom_violin(), geom_text() with facet_grid() to print total number of rows in each factor excluding NA
在下面的小提琴图中,我想添加用于绘制每个图的总行数,不包括 NA
值。
输入:
df <- cbindX(as.data.frame(rep(c(rep("trt", 4*500), rep("trt2",4*500)),2)),
as.data.frame(rnorm(15*500,2)),
as.data.frame(c(rep("A", 8*500), rep("B", 8*500))))
colnames(df) <- c("variable", "value", "mark")
代码:
ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) + geom_text(aes(x = variable, y = -2, label=nrow(df)),color="red")
输出:
预期输出:
这个锻炼适合你吗
ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) + annotate("text", label = "4000", x =1, y = -3, size = 10, colour = "black") + annotate("text", label = "3500", x =2, y = -3, size = 10, colour = "black")
这应该对您有帮助:
library(dplyr)
count<-df %>% filter(!is.na(value)) %>%
group_by(variable) %>%
summarise(n=n()) %>%
as.data.frame
# variable n
# 1 trt 4000
# 2 trt2 3500
ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) +
geom_text(data=count,aes(x = variable, y = -2, label=n),color="red")
在下面的小提琴图中,我想添加用于绘制每个图的总行数,不包括 NA
值。
输入:
df <- cbindX(as.data.frame(rep(c(rep("trt", 4*500), rep("trt2",4*500)),2)),
as.data.frame(rnorm(15*500,2)),
as.data.frame(c(rep("A", 8*500), rep("B", 8*500))))
colnames(df) <- c("variable", "value", "mark")
代码:
ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) + geom_text(aes(x = variable, y = -2, label=nrow(df)),color="red")
输出:
这个锻炼适合你吗
ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) + annotate("text", label = "4000", x =1, y = -3, size = 10, colour = "black") + annotate("text", label = "3500", x =2, y = -3, size = 10, colour = "black")
这应该对您有帮助:
library(dplyr)
count<-df %>% filter(!is.na(value)) %>%
group_by(variable) %>%
summarise(n=n()) %>%
as.data.frame
# variable n
# 1 trt 4000
# 2 trt2 3500
ggplot(df,aes(x=variable,y=value)) + geom_violin(trim = T) +
geom_text(data=count,aes(x = variable, y = -2, label=n),color="red")