r - 饼图 - 如何在正确的位置获取百分比文本?

标签 r ggplot2 pie-chart

我无法在饼图的正确位置显示百分比信息。有人可以非常友好地帮助我吗?非常感谢!

        #sample dataframe       
        d <- data.frame(facet=c('a','b','c', "d"), value=c('0.46','0.11','0.18', "0.25"))
        d$value <- as.numeric(as.character(d$value))


blank_theme <- theme_minimal()+
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    plot.title=element_text(size=14, face="bold")
  )

        d$perc <- round(d$value/sum(d$value) * 100,0)
        d$pos <-  cumsum(d$perc) - sapply(d$perc,function(x) cumsum(x)-0.5*x)

        bp <- ggplot(data=d, aes(x="", y=perc, fill=facet))+
          geom_bar(width = 1, stat = "identity") + 
          geom_text(aes(x="", y=pos, label=paste0(perc,"%"))) +
          #geom_text(aes(x="", y=value/4+ c(0, cumsum(value)[-length(value)]), label=percent(value/100))) 
          scale_fill_manual(values = c("a" = "#b2df8a", "b" = "#238b45", "c" = "#636363", "d"="orange"))
        bp

        pie <- bp +  coord_polar("y", start=0) + blank_theme +
          theme(axis.text.x=element_blank())  
        pie

enter image description here

最佳答案

碰巧由于某些原因 ggplot2 在处理标签时走向了另一个方向。因此,而不是使用

d$pos <-  100 - (cumsum(d$perc) - sapply(d$perc, function(x) cumsum(x) - 0.5 * x))

给予

enter image description here

关于r - 饼图 - 如何在正确的位置获取百分比文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612267/

相关文章:

mysql - 错误 : R cannot connect to MySQL

r - 在 R 中,如何连接和子集 SpatialPolygonsDataFrame?

linux - 在 R ("No such file or directory"中安装包(AlgDesign 和 ggplot2)时出现问题

r - 在 R 中调整帕累托图上的第二个 y 轴

r - 努力将 1 分钟收盘价数据转换为 R 中的 5 分钟

r - 使用 ggplot2 时,我可以设置直方图条的颜色而不会掩盖低值吗?

r - 如何从具有相对频率的表中绘制 R 中的饼图?

javascript - Highcharts:如何动态移动项目图例位置

graph - 饼图中的负值

R 没有列出文件夹中的所有文件