本文是回到B站關(guān)注者的提問龄恋,他的問題如下
原始數(shù)據(jù)存儲在一個(gè)excel文件里聋亡,這個(gè)excel文件里有三個(gè)子表格汰蓉,每一個(gè)子表格的數(shù)據(jù)如下:
總的數(shù)據(jù)格式
現(xiàn)在的需要是做如下的圖
接下來就介紹如何利用原始數(shù)據(jù)到最終的圖的ggplot2的代碼
首先是將3個(gè)子表格的數(shù)據(jù)整理到一張表格里
比如這里我新建了一個(gè)子表格sheet4,數(shù)據(jù)最終的格式如下
接下來R語言里操作
首先是讀取數(shù)據(jù)
library(readxl)
df<-read_excel("prac.xlsx",
sheet = "sheet4")
df
將寬格式轉(zhuǎn)換為長格式
library(tidyverse)
df %>%
pivot_longer(!var4) -> new_df
new_df
定義誤差線函數(shù)
這里用到的是標(biāo)準(zhǔn)誤
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")
調(diào)整不同分組之間的順序
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")
調(diào)整組內(nèi)柱子之間的順序
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")
這里新學(xué)到一個(gè)知識點(diǎn)是珊佣,柱子默認(rèn)是不貼底的康铭,如果要貼底使用函數(shù)scale_y_continuous(expand = expansion(mult = c(0,0.1)))
mult對應(yīng)的兩個(gè)值一個(gè)是控制下面惯退,一個(gè)是控制上面,貼底就設(shè)置為0 就可以了
公眾號推文由獲取數(shù)據(jù)和代碼的方式
歡迎大家關(guān)注我的公眾號
小明的數(shù)據(jù)分析筆記本
小明的數(shù)據(jù)分析筆記本 公眾號 主要分享:1从藤、R語言和python做數(shù)據(jù)分析和數(shù)據(jù)可視化的簡單小例子催跪;2、園藝植物相關(guān)轉(zhuǎn)錄組學(xué)夷野、基因組學(xué)懊蒸、群體遺傳學(xué)文獻(xiàn)閱讀筆記;3悯搔、生物信息學(xué)入門學(xué)習(xí)資料及自己的學(xué)習(xí)筆記骑丸!