原始數據存儲在一個excel文件裡,這個excel文件裡有三個子表格,每一個子表格的數據如下:
image.png總的數據格式
image.png現在的需要是做如下的圖
image.png接下來就介紹如何利用原始數據到最終的圖的ggplot2的代碼
首先是將3個子表格的數據整理到一張表格裡比如這裡我新建了一個子表格sheet4,數據最終的格式如下(原始數據裡第一列的編號是沒有用的,可以直接刪掉)
image.png接下來R語言裡操作
首先是讀取數據library(readxl)
df<-read_excel("prac.xlsx",
sheet = "sheet4")
df
將寬格式轉換為長格式library(tidyverse)
df %>%
pivot_longer(!var4) -> new_df
new_df
定義誤差線函數這裡用到的是標準誤
ebtop<-function(x){
return(mean(x)+sd(x)/sqrt(length(x)))
}
ebbottom<-function(x){
return(mean(x)-sd(x)/sqrt(length(x)))
}
ggplot2作圖library(ggplot2)
ggplot(data=new_df,aes(x=name,y=value,fill=var4))+
stat_summary(geom = "bar",fun = "mean",
position = position_dodge(0.9))+
stat_summary(geom = "errorbar",
fun.min = ebbottom,
fun.max = ebtop,
position = position_dodge(0.9),
width=0.2)+
scale_y_continuous(expand = expansion(mult = c(0,0.1)))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("#e20612","#ffd401","#00b0eb"),
name="")+
labs(x="XXXXX",y="YYYYY")
image.png調整不同分組之間的順序new_df$name<-factor(new_df$name,
levels = c("var2","var3","var1"))
ggplot(data=new_df,aes(x=name,y=value,fill=var4))+
stat_summary(geom = "bar",fun = "mean",
position = position_dodge(0.9))+
stat_summary(geom = "errorbar",
fun.min = ebbottom,
fun.max = ebtop,
position = position_dodge(0.9),
width=0.2)+
scale_y_continuous(expand = expansion(mult = c(0,0.1)))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("#e20612","#ffd401","#00b0eb"),
name="")+
labs(x="XXXXX",y="YYYYY")
image.png調整組內柱子之間的順序new_df$var4<-factor(new_df$var4,
levels = c("group2",
"group3",
"group1"))
ggplot(data=new_df,aes(x=name,y=value,fill=var4))+
stat_summary(geom = "bar",fun = "mean",
position = position_dodge(0.9))+
stat_summary(geom = "errorbar",
fun.min = ebbottom,
fun.max = ebtop,
position = position_dodge(0.9),
width=0.2)+
scale_y_continuous(expand = expansion(mult = c(0,0.1)))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("#e20612","#ffd401","#00b0eb"),
name="")+
labs(x="XXXXX",y="YYYYY")
image.png這裡新學到一個知識點是,柱子默認是不貼底的,如果要貼底使用函數scale_y_continuous(expand = expansion(mult = c(0,0.1)))
mult對應的兩個值一個是控制下面,一個是控制上面,貼底就設置為0 就可以了
還有一個知識點是 expand.grid(x=c(1,2,3),y=c(4,5,6)) 可以生成兩兩配對的數據
如果需要示例數據和代碼的話,可以給推文打賞1元。如果沒有收到我的回覆,可以添加我的微信mingyan24催我
歡迎大家關注我的公眾號
小明的數據分析筆記本
小明的數據分析筆記本 公眾號 主要分享:1、R語言和python做數據分析和數據可視化的簡單小例子;2、園藝植物相關轉錄組學、基因組學、群體遺傳學文獻閱讀筆記;3、生物信息學入門學習資料及自己的學習筆記!