Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pie plot getting its text on top of each other

Tags:

r

ggplot2

Just trying to fix this overlapped labeling:

My code:

  values=c(164241,179670)
  labels=c("Private", "Public")
  colors=c("#cccccc", "#aaaaaa")
  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 )

  pie <- ggplot(values, aes(x = "", y = val, fill = Type)) + geom_bar(width = 1) + 
          geom_text(aes(y = **val + 1**, **hjust=0.5**, **vjust=-0.5**, label = percent), colour="#333333", face="bold", size=10) +
          coord_polar(theta = "y") + ylab(NULL) + xlab(NULL) +
          scale_fill_manual(values = graph$colors) + labs(fill = graph$categoriesName) +
          opts( title = graph$title, 
                axis.text.x = NULL,
                plot.margin = unit(c(0,0,0,0), "lines"), 
                plot.title = theme_text(face="bold", size=14), 
                panel.background = theme_rect(fill = "white", colour = NA) )
  print(pie)

Tried messing with the values marked with asterisks (** **) but haven't got anywhere. Any help appreciated.

like image 203
fabiopedrosa Avatar asked Jan 21 '12 09:01

fabiopedrosa


People also ask

How can you avoid overlapping labels in a pie chart?

Use pie() method to plot a pie chart with slices, colors, and slices data points as a label. Make a list of labels (those are overlapped using autopct). Use legend() method to avoid overlapping of labels and autopct. To display the figure, use show() method.

How do you prevent data labels from overlapping in Excel pie chart?

Labels may overlap if the pie chart contains too many slices. One solution is to display the labels outside the pie chart, which may create more room for longer data labels. If you find that your labels still overlap, you can create more space for them by enabling 3D.


1 Answers

here is an example:

pie <- ggplot(values, aes(x = "", y = val, fill = Type)) + 
  geom_bar(width = 1) + 
  geom_text(aes(y = val/2 + c(0, cumsum(val)[-length(val)]), label = percent), size=10)
pie + coord_polar(theta = "y")

enter image description here

Perhaps this will help you understand how it work:

pie + coord_polar(theta = "y") + 
  geom_text(aes(y = seq(1, sum(values$val), length = 10), label = letters[1:10]))

enter image description here

like image 126
kohske Avatar answered Nov 02 '22 17:11

kohske