R語言之可視化②點圖

主要內容:

  • 準備數據
  • 基本點圖
  • 在點圖上添加摘要統計信息
  • 添加平均值和中位數
  • 帶有盒子圖和小提琴圖的點圖
  • 添加平均值和標準差
  • 按組更改點圖顏色
  • 更改圖例位置
  • 更改圖例中項目的順序
  • 具有多個組的點圖
  • 定製的點圖
  • 相關信息

第一步:準備數據,使用的數據包括三列,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

也可以使用以下功能手動更改點圖顏色:

  • scale_fill_manual():使用自定義顏色
  • scale_fill_brewer():使用RColorBrewer包中的調色板
  • scale_fill_grey():使用灰色調色板
# 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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章