Home > OS >  ggplot label placement for doughnut plot
ggplot label placement for doughnut plot

Time:04-09

I've decided to go against the general rules and produce a doughnut plot. The plot itself is fine (pretty even), but I can't seem to get the labels to go in the right spot. I'll bet it's something trivial, but I just can't see it.

Here's the code:

mdat <- data.frame(
      category = c("C", "E", "I", "L", "Mi", "Mo", 
      "O", "Q", "S", "V"), 
      ct = c(147, 275, 431, 967, 121, 105, 17, 186, 620, 42))

mdat$category <- factor(mdat$category, levels = mdat$category)

# Fractions
mdat$fraction <- mdat$ct / sum(mdat$ct)

# Cumulative fractions; this forms the top of each rectangle
mdat$ymax <- cumsum(mdat$fraction)

# This will the the bottom of the rectangle
mdat$ymin <- c(0, head(mdat$ymax, n = -1))

# Label position - this isn't right
mdat$labelPosition <- ((mdat$ymax   mdat$ymin) / 2) 

# Labels
mdat$label <- paste0(mdat$category, " Fraction: \n", 
      round(mdat$ct/sum(mdat$ct), 4) * 100, "%")

# Plot
g <- ggplot(mdat, aes(ymax = ymax, ymin = ymin, xmax = 11, xmin = 10, 
      fill = category))
g <- g   geom_rect()
g <- g   geom_label(x = 2, aes(y = labelPosition, label = label), size = 3)
g <- g   scale_fill_brewer(palette = "Set3")
g <- g   scale_color_brewer(palette = "Set3")
g <- g   coord_polar(theta = "y")
g <- g   xlim(c(7, 12))
g <- g   theme_void()
g <- g   theme(legend.position = "none")
g

Here's the plot generated by the code: doughnut plot with labels in the wrong place

They might be off by a partial rotation? I'm just not seeing it.

Thanks.

CodePudding user response:

The donut chart is just a stacked bar chart in polar coordinates. So if you choose your x within geom_label() below the lower boundary within xlim(), the labels wander off to the opposite side of the plot.

   g <- ggplot(mdat, aes(ymax = ymax, ymin = ymin, xmax = 11, xmin = 10, 
                          fill = category))
    g <- g   geom_rect()
    g <- g   geom_label(x = 12.1, aes(y = labelPosition, label = label), size = 3)
    g <- g   scale_fill_brewer(palette = "Set3")
    g <- g   scale_color_brewer(palette = "Set3")
    g <- g   coord_polar(theta = "y")
    g <- g   xlim(c(7, 12))
    g <- g   theme_void()
    g <- g   theme(legend.position = "none")
    g

enter image description here

  • Related