美文网首页
ggplot2 学习day2

ggplot2 学习day2

作者: Silmarillion123 | 来源:发表于2020-05-29 17:17 被阅读0次

其实不需要去寻找数据,gcookbook 就有演示数据

1.条型图

非连续型:

> pg_mean
  group weight
1  ctrl  5.032
2  trt1  4.661
3  trt2  5.526
>ggplot(pg_mean,aes(x=group,y=weight))+geom_bar(stat="identity")
image.png
ggplot(pg_mean,aes(x=group,y=weight))+geom_bar(stat="identity",width=0.5)width可控制条形间距
image.png

连续型:
若不加处理
ggplot(BOD,aes(x=Time,y=demand))+geom_bar(stat="identity")

image.png
若转化为离散型
ggplot(BOD,aes(x=factor(Time),y=demand))+geom_bar(stat="identity")#用factor函数
image.png
花炮一点的话
ggplot(BOD,aes(x=factor(Time),y=demand))+geom_bar(stat="identity",fill="lightblue",colour="black") image.png

2.簇状条形图

ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+geom_bar(position = "dodge",stat="identity")
fill 指根据Cultivar这一个参数来分配颜色
position = "dodge" 使条形在水平方向上错开

image.png
ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+geom_bar(position = "dodge",stat="identity",color="blue")+scale_fill_brewer(palette="Pastell")最后一句为换一个调色盘 image.png

3.频数条形图

ggplot(diamonds,aes(x=cut))+geom_bar()

image.png

4.颜色改变示例

a<-subset(uspopchange,rank(Change)>40)#从小到大排,40名以后的
ggplot(a,aes(x=Abb,y=Change,fill=Region))+geom_bar(stat="identity")#基础版

ggplot(a,aes(x=Abb,y=Change,fill=Region))+geom_bar(stat="identity")+geom_text(aes(label=Change),vjust=1.5,colour="yellow")
给条形增加数值,vjust正的在下,负的在上
image.png

ggplot(a,aes(x=Abb,y=Change,fill=Region))+geom_bar(stat="identity")+geom_text(aes(label=Change),vjust=-0.5,colour="black")

image.png

ggplot(a,aes(x=Abb,y=Change,fill=Region))+geom_point(size=5)
这叫做cleverland点图

image.png
ggplot(a,aes(x=reorder(Abb,Change),y=Change,fill=Region))+geom_bar(stat="identity",color="black")+scale_fill_manual(values=c("#669933","#FFCC66"))+xlab("State")

reoerder函数可将一个因子根据另一个变量进行排序
在aes内进行颜色映射设定,aes外重新设定颜色


image.png
b<-subset(climate,Source=="Berkeley"&Year>=1900)
b$pos<- b$Anomaly10y>=0
ggplot(b,aes(x=Year,y=Anomaly10y,fill=pos))+geom_bar(stat="identity",position = "identity")

创造一个新的函数来填充上色。

image.png
ggplot(b,aes(x=Year,y=Anomaly10y,fill=pos))+geom_bar(stat="identity",position = "identity",color="black",size=0.25)+scale_fill_manual(values=c("#669933","#FFCC66"),guide=FALSE) 改良版,将正负的颜色互换
image.png

5.堆积条形图

ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+geom_bar(stat="identity")+guides(fill=guide_legend(reverse =TRUE ))
如果最后一段语句不加,堆积的上下相反

image.png

相关文章

网友评论

      本文标题:ggplot2 学习day2

      本文链接:https://www.haomeiwen.com/subject/iiuzahtx.html