R | ggplot繪製帶誤差線的柱狀圖

ggplot繪製帶誤差線的柱狀圖

  1. 利用ggplot2
  2. 數據格式轉換並做統計計算
  3. 繪製圖形
## 模擬
## 導入包
library(ggplot2)
library(reshape2)
library(RColorBrewer)

## 載入數據
df <- iris
df <- melt(df, id="Species", variable.name="Attribute", value.name = "Size")
mycol= brewer.pal(n = 12, name = "Set3")

## 統計 3種鳶尾花形態數據數據均值、標準差、標準誤
mean <- aggregate(df$Size, by=list(df$Species, df$Attribute), FUN=mean)
sd <- aggregate(df$Size, by=list(df$Species, df$Attribute), FUN=sd)
len <- aggregate(df$Size, by=list(df$Species, df$Attribute), FUN=length)
df_res <- data.frame(mean, sd=sd$x, len=len$x)
colnames(df_res) = c("Species", "Attribute", "Mean", "Sd", "Count")
str(df_res)
df_res$Se <- df_res$Sd/sqrt(df_res$Count) ### 計算標準差


### ggplot 繪圖 (標準差:誤差線)
ggplot(df_res, aes(x=Attribute, y=Mean, fill=Species)) +
  geom_bar(stat="identity", position=position_dodge(),color="black", width=.6) +
  scale_fill_manual(values = mycol) +
  geom_errorbar(aes(ymin=Mean-Sd, ymax=Mean +Sd),position=position_dodge(.6), width=.2)
  theme_bw()

  ggplot(df_res, aes(x=Attribute, y=Mean, fill=Species)) +
    geom_bar(stat="identity", position=position_dodge(),color="black", width=.6) +
    scale_fill_manual(values = mycol) +
    geom_errorbar(aes(ymin=Mean-Sd, ymax=Mean +Sd),position=position_dodge(.6), width=.2) +
  theme_bw()

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章