如何使用ggplot画条形图并调整背景

以前都是python中matplotlib画图,自从学会R后,用R画图更合适

# 读取数据和查询数据
taxon <- read.table("top_genus.txt")
acc <- read.table("top_genus_acc.txt")

# 导入库
library("ggplot2")

# 构建数据框用来画图
data <- data.frame(taxon=taxon, acc=acc)
colnames(data) <- c("taxon","acc")

# 画图
# 设置位置偏移0.5,宽度0.7,y轴范围【0,1】
p <- ggplot(data=data, aes(x=taxon, weight=acc, fill=taxon,color=taxon,angle = 45)) +
  geom_bar(position=position_dodge(0.5),width=0.7,show.legend=FALSE,ymin=0,ymax=1) + 
  labs(title="Acc of different model", x="Model", y="Acc")
p
# 画水平直线
p <- p+geom_hline(yintercept = c(0.9),linetype=2,color="black")
p

# 设置背景白色
p <- p+theme_bw()
p

# 去掉网格
p <- p+theme(panel.grid=element_blank(),axis.line=element_line(size=0.5, colour="black"))
p

# 调整x轴标签倾斜位置45
p <- p+theme(axis.text.x = element_text(vjust = 0.5, hjust = 0.5, angle = 45))
p

# 强制x轴从0开始(expand=c(0,0)),并设置y轴ticks
p <- p+scale_y_continuous(expand=c(0,0),breaks = c(0.0,0.2,0.4,0.6,0.8,1.0))

# 保存图形
ggsave(file="Figure2_genus.pdf",plot=p,width=6, height = 4)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44022515/article/details/105435943