Simple bar plot with multiple variables in R - Sim

2019-03-06 05:50发布

问题:

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.

回答1:

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())