Boxplot一般我们的箱线图就是这样 # Libraries library(tidyverse) library(hrbrthemes) library(viridis)
# create a dataset data <- data.frame( name=c( rep("A",500), rep("B",500), rep("B",500), rep("C",20), rep('D', 100) ), value=c( rnorm(500, 10, 5), rnorm(500, 13, 1), rnorm(500, 18, 1), rnorm(20, 25, 4), rnorm(100, 12, 1) ) )
# Boxplot basic data %>% ggplot( aes(x=name, y=value, fill=name)) + geom_boxplot() + scale_fill_viridis(discrete = TRUE, alpha=0.6, option="A") + theme_ipsum() + theme( legend.position="none", plot.title = element_text(size=11) ) + ggtitle("Basic boxplot") + xlab("") 给他加上geom_jitter:离样本点撒到上面 # Plot data %>% ggplot( aes(x=name, y=value, fill=name)) + geom_boxplot() + scale_fill_viridis(discrete = TRUE, alpha=0.6) + geom_jitter(color="black", size=0.4, alpha=0.9) + theme_ipsum() + theme( legend.position="none", plot.title = element_text(size=11) ) + ggtitle("A boxplot with jitter") + xlab("") 将箱子换成小提琴:geom_violin # Violin basic data %>% ggplot( aes(x=name, y=value, fill=name)) + geom_violin() + scale_fill_viridis(discrete = TRUE, alpha=0.6, option="A") + theme_ipsum() + theme( legend.position="none", plot.title = element_text(size=11) ) + ggtitle("Violin chart") + xlab("") # Load ggplot2 library(ggplot2) # The mpg dataset is natively available #head(mpg) # geom_boxplot proposes several arguments to custom appearance ggplot(mpg, aes(x=class, y=hwy)) + geom_boxplot( # custom boxes color="blue", fill="blue", alpha=0.2, # Notch? notch=TRUE, notchwidth = 0.8, # custom outliers outlier.colour="red", outlier.fill="red", outlier.size=3 ) 大部分人都不知道:如何映射箱子粗细,使用:varwidth = TRUE# library library(ggplot2) # create data names <- c(rep("A", 20) , rep("B", 5) , rep("C", 30), rep("D", 100)) value <- c( sample(2:5, 20 , replace=T) , sample(4:10, 5 , replace=T), sample(1:7, 30 , replace=T), sample(3:8, 100 , replace=T) ) data <- data.frame(names,value) # prepare a special xlab with the number of obs for each group my_xlab <- paste(levels(data$names),"\n(N=",table(data$names),")",sep="") # plot ggplot(data, aes(x=names, y=value, fill=names)) + geom_boxplot(varwidth = TRUE, alpha=0.2) + theme(legend.position="none") + scale_x_discrete(labels=my_xlab) 小提琴和箱线图还是放一起的好# Libraries library(ggplot2) library(dplyr) library(hrbrthemes) library(viridis)
# create a dataset data <- data.frame( name=c( rep("A",500), rep("B",500), rep("B",500), rep("C",20), rep('D', 100) ), value=c( rnorm(500, 10, 5), rnorm(500, 13, 1), rnorm(500, 18, 1), rnorm(20, 25, 4), rnorm(100, 12, 1) ) )
# sample size sample_size = data %>% group_by(name) %>% summarize(num=n())
# Plot data %>% left_join(sample_size) %>% mutate(myaxis = paste0(name, "\n", "n=", num)) %>% ggplot( aes(x=myaxis, y=value, fill=name)) + geom_violin(width=1.4) + geom_boxplot(width=0.1, color="grey", alpha=0.2) + scale_fill_viridis(discrete = TRUE) + theme_ipsum() + theme( legend.position="none", plot.title = element_text(size=11) ) + ggtitle("A Violin wrapping a boxplot") + xlab("") 欢迎加入微生信生物快来微生信生物微生信生物
|