主要内容:
第一步:准备数据,使用的数据包括三列,len长度,supp是分类变量,dose是0.5mg,1mg和2mg三个变量。
> # Convert the variable dose from a numeric to a factor variable
> ToothGrowth$dose <- as.factor(ToothGrowth$dose)
> head(ToothGrowth)
len supp dose
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10.0 VC 0.5
第二步:绘制最基础的点图,然后修改点的大小,然后翻转X,Y轴
library(ggplot2)
# Basic dot plot
p<-ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_dotplot(binaxis='y', stackdir='center')
p
# Change dotsize and stack ratio
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_dotplot(binaxis='y', stackdir='center',
stackratio=1.5, dotsize=1.2)
# Rotate the dot plot
p + coord_flip()
设置仅显示dose为0.5mg和2mg两个分组的点图
p + scale_x_discrete(limits=c("0.5", "2"))
第三步:在点图上添加摘要统计信息,使用函数stat_summary()可用于向点图中添加均值/中值点等。
# dot plot with mean points
p + stat_summary(fun.y=mean, geom="point", shape=18,
size=3, color="red")
# dot plot with median points
p + stat_summary(fun.y=median, geom="point", shape=18,
size=3, color="red")
第四步:添加箱图
# Add basic box plot
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot()+
geom_dotplot(binaxis='y', stackdir='center')
# Add notched box plot
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot(notch = TRUE)+
geom_dotplot(binaxis='y', stackdir='center')
# Add violin plot
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_violin(trim = FALSE)+
geom_dotplot(binaxis='y', stackdir='center')
第六步:添加平均值和标准差,使用函数mean_sdl。 mean_sdl计算平均值加上或减去常数乘以标准差。在下面的R代码中,使用参数mult(mult = 1)指定常量。 默认情况下,mult = 2。平均值+/- SD可以添加为交叉开关或点范围:
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_dotplot(binaxis='y', stackdir='center')
p + stat_summary(fun.data="mean_sdl", fun.args = list(mult=1),
geom="crossbar", width=0.5)
p + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1),
geom="pointrange", color="red")
第七步:按组更改点图颜色,在下面的R代码中,点图的填充颜色由剂量水平自动控制:
# Use single fill color
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_dotplot(binaxis='y', stackdir='center', fill="#FFAAD4")
# Change dot plot colors by groups
p<-ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
geom_dotplot(binaxis='y', stackdir='center')
p
也可以使用以下功能手动更改点图颜色:
# Use custom color palettes
p+scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# Use brewer color palettes
p+scale_fill_brewer(palette="Dark2")
# Use grey scale
p + scale_fill_grey() + theme_classic()