柱状图可谓是论文最常见的图表了,但有时候这种笔直排列一排的柱状图用腻了, 换种呈现方式(比如拐个弯)也可换个心情嘛,今天就先来介绍俩种构建环形柱状图的方法,分别基于ggplot2和其他的R包来绘制。
数据创建处理
Category = paste0("category", "_", 1:9)
Percent <- c(81, 77, 70, 69, 69, 68, 62, 62, 61)
Result <-data.frame(Category,Percent)
# 设置各Categroy名称
Result$Category <-
paste0(Result$Category," - ",Result$Percent,"%")
# 设置因子水平
Result$Category <-
factor(Result$Category,
levels=rev(Result$Category))
作图
ggplot(Result, aes(x = Category, y = Percent,
fill = Category)) +
geom_bar(width = 0.9, stat="identity") +
coord_polar(theta = "y") +
xlab("") + ylab("") +
ylim(c(0,100)) +
ggtitle("Top 9 Categories") +
geom_text(data = Result, hjust = 1, size = 3,
aes(x = Category, y = 0, label = Category)) +
theme_minimal() +
theme(legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank(),
axis.ticks = element_blank())
image-20210123112038513
此时发现一个问题,环最中间的Category_9俨然已经变成了一个饼图形状了,都不能称之为柱状图了,所以如何将他变为空心呢?
很简单,我们增添一些数据即可~
len <- 4
df2 <- data.frame(Category = letters[1:len], Percent = rep(0, len),
Category2 = rep("", len))
Result$Category2 <- Result$Category
# 合并数据
Result <- rbind(Result, df2)
Result$Category <-
factor(Result$Category,
levels=rev(Result$Category))
ggplot(Result, aes(x = Category, y = Percent,
fill = Category2)) +
geom_bar(width = 0.9, stat="identity") +
coord_polar(theta = "y") +
xlab("") + ylab("") +
ylim(c(0,100)) +
geom_text(data = Result, hjust = 1, size = 3,
aes(x = Category, y = 0, label = Category2)) +
theme_minimal() +
theme(legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank(),
axis.ticks = element_blank())
image-20210123112758780
此时可以发现,内层的数据已经变成柱子形状,若感觉空心较大,调整len的个数即可控制了~~
其他方法—circlize包
Circlize包circlize包可谓是做环状图神器,有时间会再深入学习这个包,因为发现该包的网址里也有类似的图形, 这里记录学习一下,有兴趣的可以去原网址学习下:https://jokergoo.github.io/circlize_book/book/ ,真的炒鸡详细,各类圈图应有尽有,只是代码不太ggplot,参数较多,额看你们自己了 ~~~
代码如下:
library(circlize)
color = rev(rainbow(length(Percent)))
circos.par("start.degree" = 90, cell.padding = c(0, 0, 0, 0))
circos.initialize("a", xlim = c(0, 100)) # 'a` just means there is one sector
circos.track(ylim = c(0.5, length(Percent)+0.5), track.height = 0.8,
bg.border = NA, panel.fun = function(x, y) {
xlim = CELL_META$xlim
circos.rect(rep(0, 9), 1:9 - 0.45, Percent, 1:9 + 0.45,
col = color, border = "white")
circos.text(rep(xlim[1], 9), 1:9,
paste(Category, " - ", Percent, "%"),
facing = "downward", adj = c(1.05, 0.5), cex = 0.8)
breaks = seq(0, 85, by = 5)
circos.axis(h = "top", major.at = breaks, labels = paste0(breaks, "%"),
labels.cex = 0.6)
})
image-20210123113021925
感觉比ggplot还好看一些,且外环添加上了百分比,细节满满,更多参数设置自己探索吧就~~
网友评论