2

我知道这个问题经常被问到,但我尝试了我找到的所有方法,但似乎没有一个有效..

这是我目前的数据。

df <- data.frame(ID = c(1,2,3,4), Type = c("A","B","A","B"), Score1 = c(10,20,30,40), Score2 = c(20,40,60,80))
ID   Type    Score1       Score2
1       A        10           20
2       B        20           40
3       A        30           60
4       B        40           80

现在我想制作一个看起来像这样的图表编辑:我放置了错误的图表>它应该看起来像这样

在此处输入图像描述

reshape我可以使用and来实现条形图ggplot

rawscore <- df[, c("Type","Score1", "Score2")]
rawscore <- melt(rawscore, id = c("Type"))
ggplot(rawscore, aes(type, value, fill=variable))+
geom_bar(stat="summary", fun.y="mean", position="dodge")

但是,我很难在图表上添加我知道应该 geom_text用来将标签放在图表上的观察次数,所以我尝试从这篇文章中创建新向量

nlabels <- table(Type)

但我有一个错误说

Error: Aesthetics must be either length 1 or the same as the data

有什么建议么?

4

2 回答 2

2
df <- data.frame(ID = c(1,2,3,4), Type = c("A","B","A","B"), Score1 = c(10,20,30,40), Score2 = c(20,40,60,80))


rawscore <- df[, c("Type","Score1", "Score2")]
rawscore <- melt(rawscore, id = c("Type"))

尝试构建另一个 data.frame ( EDIT )

library(dplyr)

dfmean <- rawscore %>% 
  group_by(interaction(variable, Type)) %>% 
  summarise(m = mean(value), count = n())
names(dfmean)[1] <- "Inter"

ggplot(rawscore, aes(x = interaction(variable, Type), y = value)) + 
  geom_bar(aes(fill = variable), stat="summary", fun.y="mean", position="dodge") +
  geom_text(data = dfmean, aes(x = Inter, y = m + 1, label = count))

在此处输入图像描述

于 2017-07-19T13:05:49.287 回答
2

@Florian 的答案略有变化。

library(dplyr)
rawscore <- df[, c("Type","Score1", "Score2")]
rawscore <- melt(rawscore, id = c("Type")) %>%
    group_by(variable) %>% summarize(value=mean(value), count = n())

ggplot(rawscore, aes(variable, value, fill=variable))+
    geom_bar(stat="identity") +
    geom_text(aes(label=count), vjust=0)

这完美地工作

在此处输入图像描述

于 2017-07-19T13:07:11.923 回答