coord_polar
函数及参数:
coord_polar(theta = 'x', #x/y
start = 0, #0-12,起始点,对应时钟刻度
direction = 1) #1/-1,顺时针/逆时针
#饼图
a <- ggplot(data = subset(diamonds,color=="E"),aes(factor('E'),
fill=cut))+geom_bar()
b <- ggplot(data = subset(diamonds,color=="E"),aes(factor('E'),
fill=cut))+geom_bar()+
coord_polar()
c <- ggplot(data = subset(diamonds,color=="E"),aes(factor('E'),
fill=cut))+geom_bar()+
coord_polar(theta = 'y')
grid.arrange(a,b,c,ncol=3)
去掉饼图中心的空白,只需将条形图的标准宽度设为1。还需去掉极坐标刻度、标签等多余的颜色。
a=ggplot(data = subset(diamonds,color=="E"),aes(factor('E'),fill=cut))+
geom_bar(width = 1)+ #设标准宽度
coord_polar(theta = 'y')
b=a+theme(axis.text = element_blank(), #去刻度标签
axis.title = element_blank(), #去标题
axis.ticks = element_blank(), #去刻度
panel.background = element_blank(), #去背景
panel.grid = element_blank()) #去网格线
grid.arrange(a,b,ncol=2)
示例比较下。
a <- ggplot(diamonds,aes(cut))+
geom_bar(width = 1,fill='deeppink1',color='black')
b <- a+coord_polar(theta = 'y')
grid.arrange(a,b,ncol=2)
细节的修饰。
data=data.frame(group=c("A","B","C","D"),
value=c(33,62,56,67))
ggplot(data,aes(x=group,y=value,fill=group))+
geom_bar(width = 0.85,stat = 'identity')+
coord_polar(theta = 'y')+
labs(x='',y='')+
ylim(c(0,75))+
#添加条柱标签
geom_text(hjust=1,size=3,aes(x=group,y=0,
label=group,color=group))+
theme(legend.position = 'none',
axis.text.y=element_blank(),
axis.ticks = element_blank())
玫瑰图
dsmall <- diamonds[sample(nrow(diamonds),1000),]
ggplot(dsmall,aes(color,fill=cut))+
geom_bar(width = 0.9)+ #使玫瑰图之间留下空隙
scale_fill_brewer(palette = 'Oranges')+
coord_polar(start = 1)+#为更好找到注释的横坐标
theme(axis.title = element_blank(),
panel.background = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank())+
annotate('text',label=levels(dsmall$color),
x=1:7,y=plyr::count(dsmall,vars = 'color')[,2]+2, #后续会讲更方便的位置参数
fontface='bold')
戒指图
#戒指图
dat=data.frame(count=c(10,60,30),category=c('A',"B","C"))
dat$fraction=dat$count/sum(dat$count)
dat=dat[order(dat$fraction),]
dat$ymax=cumsum(dat$fraction)
dat$ymin=c(0,head(dat$ymax,n=-1))
ggplot(dat,aes(fill=category,ymax=ymax,ymin=ymin,
xmax=5,xmin=3))+ #戒指粗细
geom_rect()+
coord_polar(theta = 'y')+
xlim(c(0,5))+ #此范围要包含(xmin,xmax)
theme(panel.grid = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank())+
annotate("text",x=0,y=0,label='Ring plot',
color='forestgreen',fontface='bold')+
annotate("text",x=c(4,4,4),y=c(0.05,0.25,0.7),
label=c('A','C','B'))+ #戒指环每部分添加文字
labs(title = '')+
theme(legend.position = 'none')
coord_flip
函数,x和y轴互换。
a <- ggplot(dsmall,aes(color,price))+
geom_boxplot(fill='darkgreen')+
coord_flip()
b <- ggplot(dsmall,aes(carat))+
geom_histogram(fill='hotpink',color='black')+
coord_flip()+
scale_x_reverse() #将x刻度翻转,仅适用连续型变量
grid.arrange(a,b,ncol=2)
若不翻转x轴,如下所示:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章