Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the radius of a coord_polar ggplot

I'm looking to reduce the display radius of a pie chart built in ggplot2 relative to the rest of the plot (as the defaults keep cutting off my category labels).

Here's some dummy data and code that should show you what I'm experiencing:

library(ggplot2)
library(scales)
library(grid)

Region <- c("North America", "Central America", "South America", "Carribbean",
            "Western Africa", "Northern Africa", "Southern Afica", "Eastern Africa")
Conti <- c(rep("Americas",4), rep("Africa",4))
Freq <- c(runif(8, 1, 100))
Pct <- c(Freq/sum(Freq))
Pos <- c(cumsum(360*Pct)-(360*Pct/2))
Pos <- c(ifelse(Pos<=180,Pos,Pos-180))
df <- data.frame(Region, Conti, Freq, Pct, Pos)

pl <- ggplot(df, aes(x="", y=Freq, fill=Conti)) +
  geom_bar(stat="identity", color="black", width=1) +
  coord_polar(theta='y') +
  guides(fill=guide_legend(override.aes=list(colour=NA))) +
  theme(axis.line = element_blank(),
        axis.ticks=element_blank(),
        axis.title=element_blank(),
        axis.text.y=element_blank(),
        axis.text.x=element_text(color='black', size=18, angle=90-df$Pos),
        panel.background = element_blank(),
        panel.border = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.margin = unit(0, "lines"),
        plot.background = element_rect(fill = "white"),
        plot.margin = unit(c(0, 0, 0, 0), "cm"),
        legend.position = "none") +
  scale_y_continuous(
    breaks=cumsum(df$Freq) - df$Freq/2,
    labels=paste0(df$Region," ",percent(df$Pct)))

print(pl)

If I reduce the size of the labels they become illegible relative to the pie and if I increase them they get cut-off. No matter how I try to adjust the aes(), limits, panel.margin etc. to get the balance right ggplot2 keeps automatically re-sizing the pie to occupy the same radii.

Ideally, I'd like to shrink the pie by half to allow more room for labels.

I appreciate that this isn't the prettiest plot, however, I'm updating an old figure so need to maintain the format for comparison. Any suggestions would be appreciated.

like image 611
AJD Avatar asked Dec 09 '14 07:12

AJD


1 Answers

My suggestion would be to use line breaks.

pl <- pl + scale_y_continuous(
  breaks=cumsum(df$Freq) - df$Freq/2,
  labels=paste0(sapply(strsplit(as.character(df$Region), " "), paste, collapse='\n'),
                "\n(", percent(df$Pct), ")"))
ggsave('pie.png', plot=pl, height=15, width=15)

enter image description here

like image 177
shadow Avatar answered Oct 03 '22 04:10

shadow