R中ggplot2条形图的预处理数据

t2a7ltrp  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(164)

如何将示例数据转换为适合ggplot2条形图的格式?(无需手动编码示例数据,如下所示)。
示例数据

df <- list()
df$group <- c("a", "a",  "a", "a","a", "b", "b", "b", "b")
df$levels <- c("1", "2", "3", "3", "3","2", "1", "3", "1")

df$freq <- interaction(df$group, df$levels)
table(df$freq)

我想成为什么样的人:

Hand-coded dataset
grp <- c(rep("a" , 3) , rep("b" , 3) )
lev <- rep(c("1" , "2" , "3") , 2)
value <- c(1, 1, 3,  2, 1, 1)
data <- data.frame(grp,lev,value)

plotted
ggplot(data, aes(fill=grp, y=value, x=lev)) + 
  geom_bar(position="dodge", stat="identity")
bnl4lu3b

bnl4lu3b1#

从绘图代码中删除stat="identity"y=value

df <- data.frame(
  group = c("a", "a",  "a", "a","a", "b", "b", "b", "b"),
  levels = c("1", "2", "3", "3", "3","2", "1", "3", "1")  
)

library(ggplot2)

ggplot(df, aes(fill = group,x = levels)) +
  geom_bar(position = "dodge")

相关问题