Simple bar plot with multiple variables in R - Similar to Excel

℡╲_俬逩灬. 提交于 2019-12-04 05:45:09

问题


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



来源:https://stackoverflow.com/questions/46916042/simple-bar-plot-with-multiple-variables-in-r-similar-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!