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.sstatic.net/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.

5
  • 2
    Did you try anything? where exactly did you get stuck? Commented Oct 24, 2017 at 16:57
  • I'd create a long rather than wide data.frame, then try ?geom_bar Commented Oct 24, 2017 at 16:57
  • Is that supposed to be Unit <- c("A", "B", "C", "D")? Otherwise, please define those variables. Commented Oct 24, 2017 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() Commented Oct 24, 2017 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? Commented Oct 24, 2017 at 20:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Your question about label placement has an answer here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.