1

I have a simple data set:

d1 <- c(">2000ppm", ">1000ppm", "<1000ppm", "<450ppm", ">2000ppm", ">1000ppm", "<1000ppm", "<450ppm") 
d2 <- c("S3", "S3", "S3", "S3", "S4", "S4", "S4", "S4") 
d3 <- c(0.0, 16.6, 83.4, 14.4, 0.8, 40.7, 59.3, 13.0)
B <- data.frame(d1,d2,d3)
colnames(B) <- c("Category", "Room", "Value")
View(B)

The value is percentages, and the sum of proportion >1000ppm and <1000ppm is naturally 100%.

This is what I have so far:

B$Category <- factor(B$Category, c("<450ppm", "<1000ppm", ">1000ppm", ">2000ppm"))

ggplot(B, aes(x=Room, y=Value, fill=Category)) +
  geom_bar(position="fill", stat="identity") +
  scale_fill_brewer()

I would like to have labels on the bar charts. How do I do that..?

The proportion >2000ppm is included in >1000ppm

– and <450ppm is of course included in the <1000ppm proportion.

It is difficult to check whether I made the bar chart correctly...

How do I construct the geom_text for the labels?

I imagine changes to be something like this: see red on picture.. http://www.bygningsfysik.dk/wp-content/uploads/2015/02/Test-3.png

Anna Heebøll
  • 101
  • 2
  • 15

1 Answers1

1

Here's one way to do it:

library(dplyr)
B %>% 
  group_by(Room) %>% 
  mutate(perc = Value / sum(Value)) %>%
  mutate(pos = cumsum(perc) - (0.5 * perc))  %>%
  ggplot(aes(x=Room, y=perc, fill=Category)) +
    geom_bar(position="fill", stat="identity") +
    scale_fill_brewer() + 
    geom_text(aes(label = sprintf("%.1f", Value), y = pos), colour = "red", size = 4) +
    labs(y = "Value")

enter image description here

(source)

Community
  • 1
  • 1
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Almost there (I changed the color to black..). This is what it looks like when I plot your code...(?!) http://www.bygningsfysik.dk/wp-content/uploads/2015/02/Result.png – Anna Heebøll Feb 26 '15 at 09:18
  • Sorry, I can't reproduce this. Looks like there's no grouping by room. – lukeA Feb 26 '15 at 09:40
  • Strange, I'm using Win7 64, R version 3.1.1, dplyr_0.4.0 & ggplot2_1.0.0. – lukeA Feb 26 '15 at 10:05