繁体   English   中英

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

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

我有这个数据框:

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)

我想在Excel中使用简单的条形图(请参见附件图): Excel Plot

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

我使用ggplot,但仅用于一个Var,如果添加其他变量,则会给我错误:

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

谢谢。

您的数据需要采用长格式而不是宽格式,才能在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)

一旦数据为长格式, 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