基本箱線圖繪制
使用ggplot2
繪制箱線圖的核心函數是geom_boxplot()
。以下是一個基礎示例,展示如何用iris
數據集繪制不同物種(Species)的萼片長度(Sepal.Length)分布:
library(ggplot2)
ggplot(iris, aes(x = Species, y = Sepal.Length)) + geom_boxplot()
顏色與填充控制
通過fill
和color
參數可分別控制箱線圖內部填充色和邊框顏色:
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + geom_boxplot(color = "black", alpha = 0.7)
alpha
參數調整透明度(0-1)- 顏色支持Hex格式(如
#FF5733
)或R顏色名稱
異常值樣式調整
箱線圖的異常值(outliers)可通過以下參數定制:
geom_boxplot(outlier.color = "red", # 異常點顏色outlier.shape = 19, # 點形狀編號outlier.size = 3, # 點大小outlier.alpha = 0.6 # 透明度
)
寬度與位置調整
width
參數控制箱體寬度,position
調整分組位置:
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + geom_boxplot(width = 0.5, position = position_dodge(0.8))
分組箱線圖
當需要按兩個分類變量分組時,使用交互變量或分面:
# 方法1:dodge分組
ggplot(mpg, aes(x = class, y = hwy, fill = factor(cyl))) + geom_boxplot(position = position_dodge(preserve = "single"))# 方法2:分面
ggplot(mpg, aes(x = class, y = hwy)) + geom_boxplot() + facet_wrap(~cyl)
統計信息顯示
可通過stat_summary()
疊加顯示均值等統計量:
ggplot(iris, aes(x = Species, y = Sepal.Length)) + geom_boxplot() +stat_summary(fun = mean, geom = "point", shape = 18, size = 3, color = "red")
水平箱線圖
交換x/y映射即可創建水平箱線圖:
ggplot(iris, aes(y = Species, x = Sepal.Length)) + geom_boxplot()
完整參數列表
geom_boxplot()
支持的完整美學參數(aesthetics)包括:
x
:分類變量(必需)y
:連續變量(必需)lower
/upper
:自定義箱體范圍middle
:自定義中位數線ymin
/ymax
:自定義須線范圍group
:強制分組變量weight
:加權箱線圖
主題定制
通過theme()
函數可精細調整標題、坐標軸等元素:
ggplot(iris, aes(x = Species, y = Sepal.Length)) + geom_boxplot() + labs(title = "鳶尾花萼片長度分布") + theme_minimal() +theme(axis.text.x = element_text(angle = 45, hjust = 1))
# 加載必要的庫
library(ggplot2)# 創建示例數據
df <- data.frame(group = rep(c("A", "B", "C"), each = 100),value = c(rnorm(150, mean = 0), rnorm(60, mean = 1), rnorm(400, mean = 2))
)# 繪制箱線圖
p <- ggplot(df, aes(x = group, y = value)) +geom_boxplot(width = 0.6, fill = "white", color = "black") + # 使用白色填充,黑色邊框labs(title = "Boxplot of Values by Group", # 標題x = "Group", # X軸標簽y = "Value") + # Y軸標簽theme_minimal() + # 使用簡潔主題theme(plot.title = element_text(size = 16, face = "bold", hjust = 0.5), # 標題樣式axis.title = element_text(size = 14, face = "bold"), # 軸標題樣式axis.text = element_text(size = 12), # 軸刻度標簽樣式legend.position = "none",axis.line = element_line(color = "black"))
# 顯示圖像
print(p)# 保存為高分辨率圖像
ggsave("boxplot.png", plot = p, width = 8, height = 6, dpi = 300)