||
参考书籍:R数据可视化手册
1. 使用ggplot()函数和geom_bar()绘制堆积条形图
library(gcookbook)
library(ggplot2)
cabbage_exp
ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity")
原始数据 | 堆积条形图 |
library(gcookbook)
library(ggplot2)
ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity")+guides(fill=guide_legend(reverse = TRUE))
图例没有调整 | 图例调整后 |
3. 使用scale_fill_brewer()函数对堆积图进行着色
library(gcookbook)
library(ggplot2)
ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity",colour="black")+
guides(fill=guide_legend(reverse = TRUE))+
scale_fill_brewer(palette = 1)
ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity",colour="black")+
guides(fill=guide_legend(reverse =FALSE))+
scale_fill_brewer(palette = 2)
reverse = TRUE,palette = 1 | reverse =FALSE,palette = 2 |
4. 在geom_text()添加数据标签之前,首先需要使用plyr()函数中arrange()函数对每组条形对应的数据进行累积求和。
#添加数据标签
library(plyr)
library(ggplot2)
#根据日期和性别对数据进行排序
ce<-arrange(cabbage_exp,Date,Cultivar)
#计算累积量
cee<-ddply(ce,"Date",transform,label_y=cumsum(Weight))
cee
ggplot(cee,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity",colour="black")+
guides(fill=guide_legend(reverse =FALSE))+
geom_text(aes(y=label_y,label=Weight),vjust=1.5,colour="White")+
scale_fill_brewer(palette = "Pastel1")
#将数据标签置于条形中部
library(plyr)
ce<-arrange(cabbage_exp,Date,Cultivar)
#计算Y轴的位置,将数据标签置于条形中部
cee1<-ddply(ce,"Date",transform,label_y=cumsum(Weight)-0.5*Weight)
ggplot(cee1,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity",colour="black")+
guides(fill=guide_legend(reverse =FALSE))+
geom_text(aes(y=label_y,label=Weight),vjust=1.5,colour="White")+
scale_fill_brewer(palette = "Pastel1")
#使用paste()函数将数据标签加上单位
library(plyr)
ce<-arrange(cabbage_exp,Date,Cultivar)
cee1<-ddply(ce,"Date",transform,label_y=cumsum(Weight)-0.5*Weight)
ggplot(cee1,aes(x=Date,y=Weight,fill=Cultivar))+
geom_bar(stat="identity",colour="black")+
geom_text(aes(y=label_y,label=paste(format(Weight,nsmall=2),"kg")),size=4)+
guides(fill=guide_legend(reverse = FALSE))+
scale_fill_brewer(palette="Pastel1")
数据标签在条形下方 | 数据标签置于条形中部 | 数据标签加单位 |
自我总结:
重点注意:添加数据标签需要先要对每组条形数据进行累积求和。
ggplot(data,aes(x,y,fill)函数+geom_bar(stat="identity")函数----绘制堆积条形图
guides(fill=guide_legend(reverse = TRUE/FALSE))-----对图例进行修改
scale_fill_brewer(palette = 1)-----颜色设置
library(plyr)
cee<-arrange(data,X,fill) fill表示分类变量
cee<-ddply(cee,"x",transform,label_y=cumsum(y))----
cee<-ddply(cee,"x",transform,label_y=cumsum(y)-0.5*y)---数据标签置于中部
geom_text(aes(y=label_y,label=Weight),vjust=1.5,colour="White")----数据标签
geom_text(aes(y=label_y,label=paste(format(Weight,nsmall=2),"kg")),size=4)---添加数据标签添加单位
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-25 08:20
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社