在R中的直方图上方添加标签

时间:2018-09-28 15:24:25

标签: r ggplot2 annotations histogram

我想绘制一个直方图,并用其他变量的平均值标记每个bin。

library(dplyr)
data(mtcars)
meanwt=mtcars %>% group_by(carb) %>% 
  dplyr::summarize(meanwt = mean(wt)) %>% pull(meanwt)
g=
  ggplot(data=mtcars, aes(x=carb, y=..count..)) +
  geom_histogram(alpha=0.3, position="identity", lwd=0.2,binwidth=1)+
  theme_bw()+
  theme(panel.border = element_rect(colour = "black", fill=NA, size=0.7))

当我绘制箱数时效果很好

##plot the count of bin  
g+stat_count(aes(y=..count..,label=..count..),geom="text",vjust=-1)

enter image description here

但是,如果我要标记其他变量的均值,则它不起作用。

#plot mean of some other variable
g+stat_summary(aes(x=carb,y=wt),xfun.y = "mean", colour = "Black", size = 2, 
               geom = "text",position=position_dodge(width=0.9), vjust=-0.25,label = meanwt)

enter image description here

有人可以帮我吗?

3 个答案:

答案 0 :(得分:2)

我不确定为什么亚历山大·亚历山大的建议没有奏效。或者,您可以使用以下方法:

dat <- mtcars %>% select(carb, wt) %>%  
  group_by(carb) %>% mutate(mean_wt = mean(wt), carb_count = n()) 
g + geom_text(data=dat, aes(carb, carb_count+0.5, label=mean_wt), color="black", check_overlap = TRUE)

enter image description here

根据董的建议!

答案 1 :(得分:1)

首先,很高兴知道您正在处理什么以及想要实现什么。在这种情况下,您要查找多少汽车具有1、2,...,8个汽缸。因此,您所需要做的就是按cyl分组并找到该类别中有多少辆汽车掉落:

mm <- mtcars %>% 
              group_by(carb) %>% 
              summarise(n = length(wt))

接下来,您可能希望使用简单的条形图针对出现次数( n )绘制 cyl

ggplot(data=mm, aes(x=carb, y=n)) +
  geom_bar(stat="identity", width=0.5, position=position_dodge(), fill = "steelblue") + 
  geom_text(aes(label=n), vjust=1.5, color="white",
            position = position_dodge(0.9), size=4)+ 
  scale_x_continuous(breaks = seq(min(mm$carb), max(mm$carb), 1)) +
  scale_y_continuous(breaks = seq(min(mm$n), max(mm$n), 1)) +
  theme_minimal()

enter image description here

答案 2 :(得分:0)

我想结合@Aleksandr和@Prradep的帮助来回答自己的问题。我不确定这是否超级容易阅读,但是对于像我这样的新手会有所帮助。

##reading the library and data
library(dplyr)
data(mtcars)

##aggregating the data (for some strange reason I have to use dplyr:: everytime I use a function within piping)
dat <- mtcars %>% dplyr::select(carb, wt) %>%  
  dplyr::group_by(carb) %>% dplyr::mutate(mean_wt = mean(wt), carb_count = n()) 

##plotting the data
ggplot(data=mtcars, aes(x=carb, y=..count..)) +
  geom_histogram(alpha=0.3, position="identity", lwd=0.2,binwidth=1)+
  theme_bw()+
  theme(panel.border = element_rect(colour = "black", fill=NA, size=0.7))+
  geom_text(data=aggregate(mean_wt~carb+carb_count,dat,mean), aes(carb, carb_count+0.5, label=round(mean_wt,1)), color="black")

enter image description here