gg_pie

gg_pie

今天尝试了一下用ggplot2画饼图,转换一下极坐标就可以实现,但是和以前画heatmap的时候不一样的是,我们在卷坐标的时候需要让数据集中在一个坐标轴上。
另一个比较有挑战性的是字符化的legend,我采用的方式是先用数字替换原始的排序方式,然后替换回来。

library(ggplot2)
labels <- c("<=5", "5~10", "10~15", "15~20", ">20")
count <- c(3549,1639,2594,2661,1548)
names(labels) <- count
sort_count <- as.numeric(names(sort(labels, decreasing = T)))
df <- data.frame(
  num = count,
  text_num = rev(cumsum(rev(count)) - rev(count)/2),
  cls = labels
)
## num text_num   cls
## 3549 3549  10216.5   <=5
## 1639 1639   7622.5  5~10
## 2594 2594   5506.0 10~15
## 2661 2661   2878.5 15~20
## 1548 1548    774.0   >20

简单画一下barplot,看图例是不是正确。
bar_plot <- ggplot(df, aes(x = "", y = num, fill = as.factor(1:5))) +   
  geom_bar(stat = "identity", width = 1, position = "stack") +      
  labs(x = "", y = "distribution of lncRNAs appear in certain number cancers", title = "") +  
  scale_fill_manual(values =c("#e21a1c", "#cc4c01", "#225ea7", "#337b4b", "#6a51a4"), labels = df$cls) +
  guides(fill=guide_legend(title = "class")) +
  geom_text(
    aes(y = text_num), 
    label = paste(as.character(round(count / sum(count), digits = 3) * 100), rep("%", 5), sep = ""),
    size = 3,
    colour = "white") +
  theme(
    axis.text.x = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank() 
    )

首先我们先得到在y轴上stack的barplot

然后我们按Y轴进行极坐标转换

bar_plot + coord_polar(theta = "y")

还有一种画法我比较喜欢

ggplot(df, aes(x = 2:6, y = num, fill = as.factor(1:5))) +   
  geom_bar(stat = "identity", width = 1, position = "stack") +   
  coord_polar(theta = "y", start = (pi * 3 / 2)) +   
  labs(x = "", y = "distribution of lncRNAs appear in certain number cancers", title = "") +
  xlim(c(1,7)) + 
  ylim(c(0, 4000)) +
  scale_fill_manual(values = c("#e21a1c", "#cc4c01", "#225ea7", "#337b4b", "#6a51a4"), labels = df$cls) +
  guides(fill=guide_legend(title = "class")) +
  geom_text(
    aes( x = 2:6, y = num/2), 
    label = paste(as.character(round(count / sum(count), digits = 3) * 100), rep("%", 5), sep = ""),
    size = 3,
    angle = 0) +
  theme_bw() +
  theme(
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank() 
    )

计算文字旋转角度

text_angle <- 45 * count / 4000 
text_angle[which(text_angle > 22.5)] <- (- 45) * count[which(text_angle > 22.5)] / 4000

posted @ 2018-03-17 10:27  PeRl`  阅读(311)  评论(0编辑  收藏  举报