【问题标题】:Limited understanding of pie charts in ggplot对ggplot中饼图的理解有限
【发布时间】:2019-11-27 23:34:33
【问题描述】:

美好的一天。我在 R 中使用了很多 ggplot。我缺少一些关于如何在ggplot 中制作饼图的基本知识。我想为变量puls$reykir 制作一个饼图,并在图表上显示百分比。下面的代码似乎画了一个饼图,但标签很奇怪。如何更改代码以便用正确位置的百分比替换奇怪的标签?这是我的代码:

puls <- read.table ("https://edbook.hi.is/gogn/pulsAll.csv", header=TRUE, sep=";")
ggplot(puls, aes(x = "", y = reykir, fill = reykir)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y", start = 0, direction = 1)

【问题讨论】:

    标签: r ggplot2 pie-chart


    【解决方案1】:

    http://www.sthda.com/english/wiki/ggplot2-pie-chart-quick-start-guide-r-software-and-data-visualization

    您需要转换表格,以便有一个包含计数的值列。这张图是您要找的吗?

    # convert to data.table 
    # install.packages("data.table") # for installing
    library(data.table)
    dt <- as.data.table(puls)
    
    # .N getsthe count of the rows by reykir
    dt2 <- dt[, .N, by=reykir]
    # turn in to probability & view
    dt2[, P := N/sum(N)]
    dt2[]
    
    # change y to P and add in the scale_y_continous for percent
    ggplot(dt2, aes(x = "", y = P, fill = reykir)) +
      geom_bar(stat = "identity") +
      scale_y_continuous(labels = scales::percent) + 
      geom_text(aes(label=paste0(round(100*P, 1), "%")), position = position_stack(vjust=.5)) + 
      coord_polar(theta = "y", start = 0, direction = 1)  + 
      theme_minimal()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多