1

I have this data frame:

Unit <- c(A, B, C, D)
Yes <- c(50, 65, 20, 41)
No <- c(70, 67, 40, 20)
Missing <- c(10, 12, 8, 7)
df <- data.frame(Unit, Yes, No, Missing)

I want to use simple bar plot such as in Excel (Please see attached plot):Excel Plot

https://i.stack.imgur.com/BvWSA.jpg

I used ggplot but only for one Var, If I add others it gave me error:

ggplot(data = df, aes(x = Unit, y = Yes)) +
  geom_col() +
  geom_text(aes(label = Yes), position = position_stack(vjust = 0.5))

Thank you.

Vip
  • 41
  • 1
  • 1
  • 4
  • 2
    Did you try anything? where exactly did you get stuck? – MrFlick Oct 24 '17 at 16:57
  • I'd create a long rather than wide `data.frame`, then try `?geom_bar` – juan Oct 24 '17 at 16:57
  • Is that supposed to be `Unit <- c("A", "B", "C", "D")`? Otherwise, please define those variables. – r2evans Oct 24 '17 at 17:04
  • Try with `gather` i.e. `gather(df, key, val, -Unit) %>% group_by(Unit, key) %>% ggplot(., aes(x = Unit, y = val, fill = key)) + geom_col()` – akrun Oct 24 '17 at 17:04
  • how can I use geom_bar to plot all variables (Yes, No, Missing) for all Units (A,B,C, and D) ? Can I do that in one plot such in the attached pic in the original post? – Vip Oct 24 '17 at 20:57

1 Answers1

6

Your data needs to be in long format, not wide format, to plot in ggplot

Unit <- c("A", "B", "C", "D") #character objects need quotes
Yes <- c(50, 65, 20, 41)
No <- c(70, 67, 40, 20)
Missing <- c(10, 12, 8, 7)
df <- data.frame(Unit, Yes, No, Missing)

require(tidyr)
df.long <- gather(df, variable,value, -Unit)

Once the data is in long format, position_dodge() will give you the graph you want

ggplot(data = df.long, aes(x = Unit, y = value, fill = variable)) +
  geom_col(position = position_dodge()) 

plot

fishtank
  • 3,718
  • 1
  • 14
  • 16
Jan Boyer
  • 1,540
  • 2
  • 14
  • 22
  • Hi Jan, there is one issue when I add the label to the plot, the labels is in the wrong bars !!! ggplot(data = df.long, aes(x = Unit, y = value, fill = variable)) + geom_col(position = position_dodge()) + geom_text(label = df.long$value, position = position_dodge(0.9)) + labs(y = "Count", x = "Unit") How can I arrange labels in correct bars? – Vip Oct 25 '17 at 14:08
  • Your question about label placement [has an answer here](https://stackoverflow.com/questions/30634148/issue-with-geom-text-when-using-position-dodge) – Jan Boyer Oct 25 '17 at 16:21