简体   繁体   English

R中具有多个变量的简单条形图-类似于Excel

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

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 我想在Excel中使用简单的条形图(请参见附件图): Excel Plot

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

I used ggplot but only for one Var, If I add others it gave me error: 我使用ggplot,但仅用于一个Var,如果添加其他变量,则会给我错误:

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

Thank you. 谢谢。

Your data needs to be in long format, not wide format, to plot in ggplot 您的数据需要采用长格式而不是宽格式,才能在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 一旦数据为长格式, position_dodge()将为您提供所需的图形

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

情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM