[R] ggplot: Stacked bar/pie chart - Objects above the bar/pie

Gunnar Oehmichen oehm8895 at uni-landau.de
Fri Oct 17 12:52:04 CEST 2014


Hello,

I would like to draw a circle on top of a pie chart (The plot does not
need to fullfill scientific standards). The circle represents the
relation of a reference-value in comparison to the summed values of the
pie-pieces. To be able to do this I partly followed:
http://rpubs.com/RobinLovelace/11641 . But i have the problem of some
bar/pie pieces being placed above the stacked bar/outside of the pie
chart, see graph PA / PA + coord_polar.

System: $platform [1] "i686-pc-linux-gnu"; $version.string [1] "R
version 3.1.1 (2014-07-10)"; ggplot2_0.9.3.1

####

require (ggplot2)

mdf <- structure(list(
  VG = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L),
                 .Label = c("A", "B"), class = "factor"),
  variable = structure(c(4L, 3L, 5L, 1L, 2L, 1L, 4L, 3L, 2L, 5L),
                       .Label = c("a", "b", "c",  "d", "e"), class =
"factor"),
  value = c(0, 8407346.56, 0, 124901773, 0, 184987520, 14612608,
3165030, 0, 0),
  reference = c(0.75, 0.75, 0.75, 0.75, 0.75, 1.25, 1.25, 1.25, 1.25,
1.25)),
  .Names = c("VG", "variable", "value", "reference"),
  row.names = c(16L, 17L, 18L,   19L, 20L, 46L, 47L, 48L, 49L, 50L),
class = "data.frame")

# Calculate position
pos <- function (x) 0.5 * (cumsum(x) + cumsum(c(0, x[-length(x)])))
lmdf <- dlply (mdf, "VG")
lmdf <- lapply (lmdf, function (X) { X$pos <- pos (X$value)
                             return (X) })
mdf <- rbind.data.frame (lmdf[[1]], lmdf[[2]])

# height (radius) of all pieces (variable) in one bar (pie) will be the
same:
mdf$rad <- 1

# abline from the reference column in the dataframe
INTCA <- unique (mdf$reference[mdf$VG=="A"])
PA <- ggplot (mdf[mdf$VG=="A",], aes (x = pos, y = rad)) +
  geom_bar (stat = "identity", aes (fill = variable, width = value)) +
  geom_abline(intercept = INTCA, slope = 0)

PA
PA + coord_polar()
# Object c is placed above its position on the y axis

# abline from the reference column in the dataframe
INTCB <- unique (mdf$reference[mdf$VG=="B"])
PB <- ggplot (mdf[mdf$VG=="B",], aes (x = pos, y = rad)) +
  geom_bar (stat = "identity", aes (fill = variable, width = value)) +
  geom_abline(intercept = INTCB, slope = 0)

PB
PB + coord_polar()
# all objects are within rad = 1

###

Your help would be very much appreciated,

Gunnar



More information about the R-help mailing list