所展示的图形都是在Rmarkdown上输出的结果,由于大小限制的原因,有些走样,将图片保存到本地效果会好很多。参考[1] 简书: https://www.jianshu.com/p/a272391297e0R语言科研绘图(2)
需要导入包
library(ggplot2)
library("ggpubr")
library(ggsci)
library(gridExtra)绘制分组条形图
setwd("xx\\barplotGroup")
library(ggplot2)
library("ggpubr") #引用包
inputFile="input.txt" #输入
outFile="barplot.png" #输出
rt=read.table(inputFile,header=T,sep="\t",check.names=F) #读取输入文件
#绘制
# png(file=outFile,width=7,height=5)
ggbarplot(rt, x="Term", y="Count", fill = "ONTOLOGY", color = "white",
orientation = "horiz", #横向显示
palette = "aaas", #配色方案
legend = "right", #图例位置
sort.val = "asc", #上升排序,区别于desc
sort.by.groups=TRUE)+ #按组排序
scale_y_continuous(expand=c(0, 0)) + scale_x_discrete(expand=c(0,0))
绘制密度图
#library(ggsci)
#library(gridExtra)
png(file=density.png,width=7,height=5)
set.seed(1234)
wdata = data.frame(
sex = factor(rep(c("F", "M"), each=200)),
weight = c(rnorm(200, 55), rnorm(200, 58)))#200个随机数,平均数是55
p=ggdensity(wdata, x = "weight",
add = "mean", rug = TRUE,
color = "sex", fill = "sex",
palette = c("#00AFBB", "#6495ED"))
p1_a=p+scale_color_aaas()
p2_a=p+scale_fill_aaas()
p3=grid.arrange(p1_a,p2_a,ncol=2)
ggsave(p3,file="density.png",height=10,width=10) # 保存图片绘制分布图
p1=gghistogram(wdata,x="weight",
add="mean",rug=TRUE,
color="sex",fill="sex",palette=c("#00AFBB", "#6495ED"))
p1_b=p1+scale_color_igv()
p2_b=p1+scale_fill_igv()
p3_b=grid.arrange(p1_b,p2_b,ncol=2)
# ggsave(p3_b,file="histogram.pdf",height=12,width=10)排序柱状图
data("mtcars")
df2 <- mtcars
df2$cyl <- factor(df2$cyl)
df2$name <- rownames(df2) #添加一行name
dfm=df2
dfm$mpg_z <- (dfm$mpg -mean(dfm$mpg))/sd(dfm$mpg)
dfm$mpg_grp <- factor(ifelse(dfm$mpg_z < 0, "low", "high"),
levels = c("low", "high"))
p2=ggbarplot(dfm, x = "name", y = "mpg_z",
fill = "mpg_grp", # change fill color by mpg_level
color = "white", # Set bar border colors to white
palette = "jco", # jco journal color palett. see ?ggpar
sort.val = "asc", # Sort the value in ascending order
sort.by.groups = FALSE, # Don't sort inside each group
x.text.angle = 90, # Rotate vertically x axis texts
ylab = "MPG z-score",
xlab = FALSE,
legend.title = "MPG Group"
)
p2_a=p2+scale_color_lancet()
p2_b=p2+scale_fill_lancet()
p3_2=grid.arrange(p2_a,p2_b,ncol=2)
p3_2
ggsave(p3_2,file="sort.pdf",height=12,width=10)竖着排列
p4=ggbarplot(dfm, x = "name", y = "mpg_z",
fill = "mpg_grp", # change fill color by mpg_level
color = "white", # Set bar border colors to white
palette = "jco", # jco journal color palett. see ?ggpar
sort.val = "desc", # Sort the value in descending order
sort.by.groups = FALSE, # Don't sort inside each group
x.text.angle = 90, # Rotate vertically x axis texts
ylab = "MPG z-score",
legend.title = "MPG Group",
rotate = TRUE,
ggtheme = theme_minimal()
)
p4_a=p4+scale_color_d3()
p4_b=p4+scale_fill_d3()
p3_3=grid.arrange(p4_a,p4_b,ncol=2)
p3_3
ggsave(p3_3,file="sort2.pdf",height=12,width=10)参考资料