R可视化:圆环图

作者: 生信学习者2 | 来源:发表于2023-04-06 16:00 被阅读0次

    圆环图相比饼图更好看一些(个人感觉)

    数据准备

    # 加载R包
    library("ggplot2") 
    library("dplyr") 
    
    # 数据准备
    plotdata <- data.frame(
      class = c("1st", "2nd", "3rd", "Crew"),
      n = c(325, 285, 706, 885),
      prop = c(14.8, 12.9, 32.1, 40.2)
    )
    
    # 按照分组排序添加标签的位置信息
    plotdata <- plotdata %>%
      arrange(desc(class)) %>%
      mutate(lab.ypos = cumsum(prop) - 0.5*prop) %>% # 标签放置在中心位置
      mutate(num_prop = paste0("n = ", n, "\n", 
                               paste0(prop, "%")))
    

    饼图

    • ggplot2画饼图函数: geom_bar() + coord_polar().
    • 添加百分比函数: geom_text()
    • 配置映射背景颜色函数: scale_color_manual()
    • 设置主题函数:theme_void()
    mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF")
    ggplot(plotdata, aes(x = "", y = prop, fill = class)) +
      geom_bar(width = 1, stat = "identity", color = "white") +
      coord_polar("y", start = 0)+
      geom_text(aes(y = lab.ypos, label = prop), color = "white")+
      scale_fill_manual(values = mycols) +
      theme_void()
    

    圆环图

    • x=2xlim(0.5, 2.5)设置中间圆环的大小
    p <- ggplot(plotdata, aes(x = 2, y = prop, fill = class)) +
      geom_bar(stat = "identity", color = "white") +
      coord_polar(theta = "y", start = 0)+
      geom_text(aes(y = lab.ypos, label = num_prop), color = "white")+
      scale_fill_manual(values = mycols) +
      theme_void()+
      xlim(0.5, 2.5)
    p
    

    尝试把legend放到中间圆环过,但是没有成功,大家有什么好办法吗?

    • 圆环内部添加其他信息: annotate
    p + annotate("text", x = 1, y = 1, label = "donut chart")
    

    Reference

    相关文章

      网友评论

        本文标题:R可视化:圆环图

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