生成隨機數據
在R中,可以使用rnorm()
生成正態分布的隨機數據,并模擬分組數據。以下代碼生成3組(A、B、C)隨機數據,每組包含10個樣本:
set.seed(123) # 確保可重復性
group_A <- rnorm(10, mean=50, sd=5)
group_B <- rnorm(10, mean=60, sd=8)
group_C <- rnorm(10, mean=45, sd=6)
data <- data.frame(Group = rep(c("A", "B", "C"), each=10),Value = c(group_A, group_B, group_C)
)
計算均值和標準偏差
使用dplyr
包匯總數據,計算每組均值和標準偏差:
library(dplyr)
summary_data <- data %>%group_by(Group) %>%summarise(Mean = mean(Value),SD = sd(Value))
繪制柱狀圖與誤差棒
使用ggplot2
繪制柱狀圖,并通過geom_errorbar
添加標準偏差誤差棒:
library(ggplot2)
ggplot(summary_data, aes(x=Group, y=Mean, fill=Group)) +geom_bar(stat="identity", width=0.5) +geom_errorbar(aes(ymin=Mean-SD, ymax=Mean+SD), width=0.2) +labs(title="誤差分析柱狀圖", y="均值 ± 標準偏差") +theme_minimal()
自定義圖形樣式(可選)
調整顏色、標題和坐標軸:
ggplot(summary_data, aes(x=Group, y=Mean, fill=Group)) +geom_bar(stat="identity", width=0.5, color="black") +geom_errorbar(aes(ymin=Mean-SD, ymax=Mean+SD), width=0.2, linewidth=0.7) +scale_fill_brewer(palette="Set2") +labs(title="誤差分析柱狀圖", x="分組", y="測量值") +theme_classic()
輸出圖形
執行代碼后,圖形將顯示在R的繪圖窗口。如需保存為文件,使用ggsave()
:
ggsave("error_bar_plot.png", width=6, height=4, dpi=300)
安裝patchwork包 在R或RStudio中執行以下命令從CRAN安裝:
install.packages("patchwork")
雙排顯示
library(ggplot2)
library(patchwork)``````r
p1 <- ggplot(summary_data, aes(x=Group, y=Mean, fill=Group)) + geom_bar(stat="identity", width=0.5) + geom_errorbar(aes(ymin=Mean-SD, ymax=Mean+SD), width=0.2) + labs(title="誤差分析柱狀圖", y="均值 ± 標準偏差") + theme_minimal()p2 <- ggplot(summary_data, aes(x=Group, y=Mean, fill=Group)) + geom_bar(stat="identity", width=0.5, color="black") + geom_errorbar(aes(ymin=Mean-SD, ymax=Mean+SD), width=0.2, linewidth=0.7) + scale_fill_brewer(palette="Set2") + labs(title="誤差分析柱狀圖", x="分組", y="測量值") + theme_classic()
左右排列顯示結果
combined_horizontal <- p1 + p2 + plot_layout(ncol = 2)
print(combined_horizontal)
combined_vertical <- p1 / p2 + plot_layout(nrow = 2)
print(combined_vertical)
combined_horizontal + plot_annotation(title = "雙圖對比分析") + plot_layout(guides = "collect") & theme(plot.margin = unit(c(1,1,1,1), "cm"))
總結
柱狀圖是所有圖像的基礎,嘗試建立不同的柱狀圖,在基本的格式基礎上更改參數,多練習多嘗試,加油吧小伙伴們。