[英]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.