下面是ggplot2绘制barplot的小例子~
1.绘制基础的条形图;
# 加载包
library(ggplot2)
# 模拟数据集
data <- data.frame(
name=c("Q","W","E","G","E","H","J","K","L","M") ,
value=c(2,14,3,17,50,68,71,64,32,99)
)
# 绘图
ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity")
2.调整条形图的宽度和颜色;
##调整图形的宽度和颜色
library(ggplot2)
data <- data.frame(
name=c("Q","W","E","G","E","H","J","K","L","M") ,
value=c(2,14,3,17,50,68,71,64,32,99)
)
ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity", width=0.5, color='#3C5488B2',fill='#00A087B2')
3.也可按照下面这个方法调整条形图的颜色(使用mtcars数据集);
library(ggplot2)
#绘图
ggplot(data=mtcars, mapping=aes(x=as.factor(cyl),fill=as.factor(cyl)))+
geom_bar(stat="count",width=0.5)+
scale_fill_manual(values=c("#3C5488B2","#00A087B2","#F39B7FB2"))+
theme(legend.position="none")
4.添加条形图的文本;
library(ggplot2)
###添加条形图的文本
ggplot(data=mtcars, mapping=aes(x=as.factor(cyl),fill=as.factor(cyl)))+
geom_bar(stat="count",width=0.5)+
scale_fill_manual(values=c("#3C5488B2","#00A087B2","#F39B7FB2"))+
geom_text(stat='count',aes(label=..count..), vjust=1.6, color="white", size=3.5)+
theme_minimal()
5.旋转坐标轴,使用coord_flip()函数即可;
library(ggplot2)
###添加条形图的文本
ggplot(data=mtcars, mapping=aes(x=as.factor(cyl),fill=as.factor(cyl)))+
geom_bar(stat="count",width=0.5)+
scale_fill_manual(values=c("#3C5488B2","#00A087B2","#F39B7FB2"))+
geom_text(stat='count',aes(label=..count..), vjust=1.6, color="white", size=3.5)+
theme_minimal()+
coord_flip()
“作图帮”公众号免费分享绘图代码与示例数据,小伙伴们可以关注一下哦~
转载:https://blog.csdn.net/weifanbio/article/details/116784420
查看评论