这里是ggplot2中的diamonds数据框中的随机抽取100条数据:
library(ggplot2)
set.seed(100)
small<-diamonds[sample(nrow(diamonds),100),]
small<-within(small,{
obj<-NA
val<-NA
obj<-c("a","b","c","d","e","f",rep(NA,94))
val<-c(2,1,3,4,7,5,rep(NA,94))}
)
data1=na.omit(small[c("obj","val")])
ggplot(data=data1,mapping=aes(x=obj,y=val,fill=obj,group=factor(1)))+
geom_bar(stat="identity")
注释:
stat=”“identity”:指定了柱状图的高度(y)
fill=obj:填充的柱状图的颜色
ggplot(data=data1,mapping=aes(x=obj,y=val,fill=obj,group=factor(1)))+
geom_bar(stat="identity",width=0.5)
data1<-within(data1,{
obj<-factor(obj,levels=c("e","f","b","c","d","a"))
})
ggplot(data=data1,mapping=aes(x=obj,y=val,fill=obj,group=factor(1)))+
geom_bar(stat="identity")
注释:
柱状图的顺序是根据因子水平顺序来排列的:
obj<-factor(obj,levels=c(“e”,”f”,”b”,”c”,”d”,”a”))
ggplot(data=data1,mapping=aes(x=obj,y=val,fill=obj,group=factor(1)))+
geom_bar(stat="identity")+
geom_text(aes(label = val, vjust = -0.8, hjust = 0.5, color = obj), show.legend = TRUE)
注释:
vjust:柱条上文字的纵坐标的位置(垂直位置,以柱条顶面线为原点)
hjust:柱条上文字的横坐标的位置(水平位置,以柱条顶面线的中点为原点)
show.legend:此文本是否包含到图例之中(NA(default),FALSE,TRUE)
这里需要先安装ggthemes包。
library(ggthemes)
ggplot(data=data1,mapping=aes(x=obj,y=val,fill=obj,group=factor(1)))+
geom_bar(stat="identity")+
geom_text(aes(label = val, vjust = -0.7, hjust = 0.5, color = obj), show.legend = TRUE)+
theme_economist()
注释:
在ggthemes中有很多的各种主题,在这里只使用了其中的theme_economist主题
ggplot(data=data1,mapping=aes(x=obj,y=val,fill=obj,group=factor(1)))+
geom_bar(stat="identity")+
geom_text(aes(label = val, vjust = -0.7, hjust = 0.5, color = obj), show.legend = TRUE)+
theme_economist()+
ylim(min(data1$val,0)*1.1,max(data1$val)*1.1)