ggplot2-饼图-值标签按相反顺序 [英] ggplot2 - piechart - value labels in reverse order

查看:390
本文介绍了ggplot2-饼图-值标签按相反顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot2将标签与饼图匹配:

I am trying to match labels with my pie chart with ggplot2:

代码:

values=c(59,4,4,11,26)
labels=c("catA", "catB","catC","catD","catE")
pos = cumsum(values)- values/2
graph <- data.frame(values, labels,pos)

categoriesName="Access"
percent_str <- paste(round(graph$values / sum(graph$values) * 100,1), "%", sep="")

values <- data.frame(val = graph$values, Type = graph$labels, percent=percent_str, pos = graph$pos )

pie <- ggplot(values, aes(x = "", y = val, fill = Type)) + 
  geom_bar(width = 1,stat="identity") + 
  geom_text(aes(x= "", y=pos, label = val), size=3) 
pie + coord_polar(theta = "y")

输出:

我阅读了这些主题,但没有成功:

I read these topics, but without any success:

  • ggplot, facet, piechart: placing text in the middle of pie chart slices
  • R + ggplot2 => add labels on facet pie chart

推荐答案

从ggplot2 2.2.0开始,您可以将position_stackvjust = .5结合使用,以将标签居中放置在堆叠条形图(以及饼图)中.您不再需要计算ggplot2之外的位置.有关这些更改的更多详细信息,请参见新闻.

Starting in ggplot2 2.2.0, you can use position_stack with vjust = .5 to center labels in stacked bars charts (and so pie charts). You no longer need to calculate the position outside of ggplot2. See the NEWS for more details on these changes.

ggplot(values, aes(x = "", y = val, fill = Type)) + 
    geom_bar(width = 1,stat="identity") + 
    geom_text(aes(label = val), size=3, position = position_stack(vjust = 0.5))  + 
    coord_polar(theta = "y")

这篇关于ggplot2-饼图-值标签按相反顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆