融化数据框的ggplot标签

时间:2018-10-25 18:06:46

标签: r ggplot2 label melt

通常我会融合数据框以在一个小节上显示多个变量。目标是创建一个geom_bar,每个变量一个参数,每个栏一个摘要标签。

例如,我将这样做:

mtcars$id<-rownames(mtcars)
tt<-melt(mtcars,id.vars = "id",measure.vars = c("cyl","vs","carb"))
ggplot(tt,aes(variable,value))+geom_bar(stat="identity")+
    geom_text(aes(label=value),color='blue')

结果是一个条形图,其中在每种情况下似乎都重复了每个条形的标签: overlapping labels

我希望每个条形都有一个标签,如下所示:

enter image description here

常见的解决方案是创建聚合值以放置在图形上,如下所示:

aggr<-tt %>% group_by(variable) %>% summarise(aggrLABEL=mean(value))

ggplot(tt,aes(variable,value))+geom_bar(stat="identity")+
    geom_text(aes(label=aggr$aggrLABEL),color='blue')

ggplot(tt,aes(variable,value))+geom_bar(stat="identity")+
    geom_text(label=dplyr::distinct(tt,value),color='blue')

但是,这些尝试分别导致错误:

对于解决方案1:错误:美学的长度必须为1或与数据(96)相同:label,x,y

对于解决方案2:[<-.data.frame*tmp*中的错误,aes_params,value = list(label = list(:替换元素1为7的矩阵/数据帧)行,需要96

那该怎么办?将geom_text设置为stat="identity"也无济于事。

1 个答案:

答案 0 :(得分:2)

我要做的是用您的列的摘要值创建另一个数据框。然后,我将在geom_text行中引用该数据框。像这样:

library(tidyverse) # need this for the %>%

tt_summary <- tt %>%
 group_by(variable) %>%
 summarize(total = sum(value))

ggplot(tt, aes(variable, value)) +
geom_col() +
geom_text(data = tt_summary, aes(label = total, y = total), nudge_y = 1) # using nudge_y bc it looks better.

enter image description here