R語言ggplot2做柱形圖如何讓起始位置不是0?之前有人在公眾號留言問過這個問題,當(dāng)時自己沒有思路,今天看到有人在公眾號留言問 下面這個圖如何實(shí)現(xiàn)。

突然有了靈感,做柱形圖的時候可以不用 geom_bar() 或者 geom_col()直接畫柱子的函數(shù),可以用geom_segment()畫線段的函數(shù),只是需要準(zhǔn)備示例數(shù)據(jù)集的時候稍微做一個調(diào)整就可以了
正常柱形圖的示例數(shù)據(jù)集如下

作圖代碼
library(readxl)
library(ggplot2)
dat01<-read_excel("data/20220601/20220601.xlsx")
dat01
ggplot(data=dat01,aes(x=var1,y=var2))+
geom_col(aes(fill=var1))

如果想讓起始位置不是0,我們準(zhǔn)備數(shù)據(jù)集如下,增加一列起始位置

作圖代碼
dat02<-read_excel("data/20220601/20220601.xlsx",
sheet = "Sheet2")
dat02
ggplot(data=dat02,aes(x=var1,xend=var1,
y=ystart,yend=yend))+
geom_segment(aes(color=var1),
size=30,
show.legend = FALSE)+
scale_y_continuous(breaks = 3:10)

接下來模仿一下推文開頭提到的圖
來自于論文 Seasonal variation in community composition and distributional ranges of birds along a subtropical elevation gradient in China 的figure4
論文中沒有找到原始數(shù)據(jù),自己構(gòu)造一份吧 只準(zhǔn)備兩個物種的數(shù)據(jù)

作圖代碼
library(ggplot2)
library(readxl)
dat03<-read_excel("data/20220601/20220601.xlsx",
sheet = "Sheet3")
dat03
ggplot(data=dat03,aes(x=species,xend=species,
y=lower,yend=upper))+
geom_segment(aes(color=season),
size=30)+
scale_color_manual(values = c("winter"="#009edc",
"both"="#93989e",
"breedingseason"="#f5c512"))+
scale_y_continuous(limits = c(700,3400),
breaks = seq(700,3400,300))+
theme_bw()+
theme(panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(linetype="dashed"),
panel.grid.minor.y = element_blank(),
axis.text.x = element_text(angle=90,
hjust=1,
vjust=0.5,
face="italic"))+
labs(x="Species",y="Elevation (m)")+
guides(color=guide_legend(override.aes = list(size = 1)))

這個只有兩個物種的數(shù)據(jù)看起來和論文中的圖差別還挺大的,物種準(zhǔn)備全了效果就是一樣的
推文的示例數(shù)據(jù)和代碼可以留言20220601獲取
歡迎大家關(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í)筆記!
