Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - piechart - value labels in reverse order

Tags:

r

ggplot2

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

Code:

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")

Output: myoutput

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
like image 222
stanedav Avatar asked Dec 19 '25 06:12

stanedav


1 Answers

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")

enter image description here

like image 123
aosmith Avatar answered Dec 21 '25 20:12

aosmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!