绘制条形图

7 篇文章 0 订阅
7 篇文章 0 订阅

绘制简单条形图

使用ggplot()函数和geom_bar(stat=‘identity’)可以绘制上述条形图

library(gcookbook)
#载入数据
ggplot(pg_mean,aes(x=group,y=weight))+geom_bar(stat='identity')

对于连续性变量,可以使用factor()函数转化成离散型变量

BOD
#没有Time=6的输入

数值型变量=连续型变量

ggplot(BOD,aes(x=Time,y=demand))+geom_bar(stat='identity')

可以看到坐标轴依然会有6

#使用factor()函数转化成离散型变量(分类)
ggplot(BOD,aes(x=factor(Time),y=demand))+geom_bar(stat='identity')

可以通过fill参数设置填充色,colour参数设置边框颜色

ggplot(pg_mean,aes(x=group,y=weight))+geom_bar(stat='identity',fill='red',colour='black')

绘制簇状条形图

簇状条形图:基于某个分类变量

与简单条形图不同的是,添加了geom_bar(position=‘dodge’)
参数的作用是使条形在水平方向上错开排列

图形函数
简单条形图geom_bar(stat=‘identity’)
簇状条形图geom_bar(position=‘dodge’)
正负值条形图geom_bar(positon=‘identity’)
#操作数据
library(gcookbook)
cabbage_exp

将Date作为x轴的数据,Cultivar作为fill填充的数据

ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+geom_bar(position='dodge',stat='identity')

Date实际应为离散型数据,在ggplot()函数中fill指定数据来源,若无position='dodge’参数,则为堆积条形图。

ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+geom_bar(stat='identity')

如果分类变量中各水平的组合中有缺失项,临近的条形将自动扩充到相应位置

ce <- cabbage_exp[1:5,]
ce

删除了最后最后一行的数据

ggplot(ce,aes(x=Date,y=Weight,fill=Cultivar)) + geom_bar(position='dodge',stat='identity',colour='black')

绘制频数条形图

不要映射任何变量到y参数,则默认使用geom_bar(stat=‘bin’),使用计数

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

条形图着色

ggplot(,fill=)+geom_bar(,colour=)+scale_fill_manual(values=)

ggplot中的fill指定变量,根据变量进行着色,geom_bar中的colour指定边框颜色,scale_fill_manual调色板函数可以指定着色的颜色,以解决默认颜色不好看的问题。

library(gcookbook)
upc <- subset(uspopchange,rank(Change)>40)
upc

颜色的映射设定是在aes内部完成的,而颜色的重新设定是在aes外部完成的。

ggplot(upc,aes(x=reorder(Abb,Change),y=Change,fill=Region))+geom_bar(stat='identity',colour='black')+scale_fill_manual(values=c('#669933','#FFCC66'))+xlab('State')

对正负条形图分别着色

#首先导入数据
library(gcookbook)
csub <- subset(climate,Source=='Berkeley' & Year >= 1900)
csub$pos <- csub$Anomaly10y >= 0

将position参数设置成’identity’可以避免系统因对负值绘制堆积条形而发出的警告信息

ggplot(csub,aes(x=Year,y=Anomaly10y,fill=pos))+geom_bar(stat='identity',position='identity')

调整条形宽度和条形间距

宽度:geom_bar()函数的参数width
条形间距:geom_bar()函数,position=position_dodge(…)
默认值都是0.9,具体可以自己调节

#导入数据
library(gcookbook)
ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar))+geom_bar(stat='identity',width=0.5,position=position_dodge(0.7))

添加数据标签

geom_text()函数可以为条形图添加数据标签,label指定标签,vjust指定竖直位置。

#导入数据
library(gcookbook)
ggplot(cabbage_exp,aes(x=interaction(Date,Cultivar),y=Weight))+geom_bar(stat='identity')+geom_text(aes(label=Weight),vjust=1,colour='white')

绘制Cleveland点图

直接运行geom_point函数,实际就是散点图

library(gcookbook)
tophit <- tophitters2001[1:25,]

ggplot(tophit,aes(x=avg,y=name))+geom_point()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值