[R] geom_text in ggplot (position)

Dennis Murphy djmuser at gmail.com
Wed May 13 12:08:29 CEST 2015


This problem is discussed in Winston Chang's R Graphics Handbook,
section 3.9. Adapting his code to this example:

test  <- data.frame(variables =  c("PE_35", "PE_49"),
                    value1=c(13,3),
                    value2=c(75,31),
                    value3=c(7,17),
                    value4 =c(5,49))

library(reshape2)
library(ggplot2)
library(plyr)

m <- melt(test, "variables")
m$cO <- gl(2, 2, length = nrow(m), labels = c("A", "B"))
m$cat <- gl(2, 4, labels = c(0, 1))


names(m)[3] <- "recuento"

mm <- ddply(m, .(variables, cat), mutate,
                   pos = cumsum(recuento) - 0.5 * recuento)   ## this
is the key part

ggplot(mm, aes(x = cat, y = recuento, fill = cO)) +
    geom_bar(stat = "identity") +
    geom_text(aes(y = pos, label = recuento)) +
    facet_wrap(~ variables)

Dennis

On Tue, May 12, 2015 at 9:50 AM, AURORA GONZALEZ VIDAL
<aurora.gonzalez2 at um.es> wrote:
> Hello everybody.
>
> I have an "esthetic" question. I have managed to create a stacked and
> grouped bar plot but I don't manage with putting the text in the middle of
> the bar plots. Do you know how to write the numbers in that position?
>
> Thank you so much.
>
> Example code:
>
> test  <- data.frame(variables =  c("PE_35", "PE_49"),
>                     value1=c(13,3),
>                     value2=c(75,31),
>                     value3=c(7,17),
>                     value4 =c(5,49))
>
> library(reshape2) # for melt
>
> melted <- melt(test, "variables")
> melted$cO <- c("A","A","B","B","A","A","B","B")
>
> melted$cat <- ''
> melted[melted$variable == 'value1' | melted$variable == 'value2',]$cat <-
> "0"
> melted[melted$variable == 'value3' | melted$variable == 'value4',]$cat <-
> "1"
>
> names(melted)[3] <- "recuento"
>
> library(ggplot2)
>
> ggplot(melted, aes(x = cat, y = recuento,ymax=max(recuento)*1.05, fill =
> cO)) +
>   geom_bar(stat = 'identity', position = 'stack', col="black") +
> facet_grid(~ variables)+
>   geom_text(aes(label = recuento), size = 5, hjust = 0.5, vjust = 1,
> position ="stack")
>
>
> ------
> Aurora González Vidal
>
> Sección Apoyo Estadístico.
> Servicio de Apoyo a la Investigación (SAI).
> Vicerrectorado de Investigación.
> Universidad de Murcia
> Edif. SACE . Campus de Espinardo.
> 30100 Murcia
>
> @. aurora.gonzalez2 at um.es
> T. 868 88 7315
> F. 868 88 7302
> www.um.es/sai
> www.um.es/ae
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list