Vip*_*Vip 1 plot r ggplot2 geom-bar
我有这个数据框:
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)
Run Code Online (Sandbox Code Playgroud)
我想使用简单的条形图,例如在 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))
Run Code Online (Sandbox Code Playgroud)
谢谢。
您的数据需要采用长格式,而不是宽格式,才能在 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)
Run Code Online (Sandbox Code Playgroud)
一旦数据为长格式,position_dodge()将为您提供您想要的图表
ggplot(data = df.long, aes(x = Unit, y = value, fill = variable)) +
geom_col(position = position_dodge())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22657 次 |
| 最近记录: |