Boxplot上的全文标签,并添加了均值 [英] full text label on Boxplot, with added mean point

查看:317
本文介绍了Boxplot上的全文标签,并添加了均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在尝试获取类似于此 https://stats.stackexchange.com的文本标签/ questions / 8206 / labeling-boxplots-in-r ,但我无法使其正常工作。 MWE与我的相似:

Am trying to get text label similar to what this https://stats.stackexchange.com/questions/8206/labeling-boxplots-in-r, but I cant get it to work. MWE similar to what I have is this:

data <- data.frame(replicate(5,sample(0:100,100,rep=TRUE)))

meanFunction <- function(x){
return(data.frame(y=round(mean(x),2),label=round(mean(x,na.rm=T),2)))}

ggplot(melt(data), aes(x=variable, y=value)) +
geom_boxplot(aes(fill=variable), width = 0.7) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=4) +
stat_summary(fun.data = meanFunction, geom="text", size = 4, vjust=1.3) 

生成的内容类似于所附图片中的 A,而我​​尝试为每个包装盒添加类似 B的字样。谢谢。

That produces something like "A" in the attached image, and I am trying to get something like "B" for each of the boxes. Thanks.

推荐答案

这是我的尝试。首先,我重塑了您的数据。然后,我制作了您的箱线图。我将文本的大小和颜色更改为均值。然后,我调查了ggplot使用的数据,您可以使用 ggplot_build(objectname)$ data [[1]] 进行访问。您可以看到所需的号码。我选择了必要的变量并重塑了数据,即 df 。使用 df ,您可以注释所需的数字。

Here is my attempt. First, I reshaped your data. Then, I produced your boxplot. I changed the size and colour of text for mean. Then, I looked into the data that ggplot used, which you can access using ggplot_build(objectname)$data[[1]]. You can see the numbers you need. I selected necessary variables and reshaped the data, which is df. Using df, you can annotate the numbers you want.

library(dplyr)
library(tidyr)
library(ggplot2)

set.seed(123)
mydf <- data.frame(replicate(5,sample(0:100,100,rep=TRUE)))

mydf <- gather(mydf, variable, value)

meanFunction <- function(x){
return(data.frame(y=round(mean(x),2),label=round(mean(x,na.rm=T),2)))}

g <- ggplot(data = mydf, aes(x = variable, y = value, fill = variable)) +
     geom_boxplot(width = 0.5) +
     stat_summary(fun.y = mean, geom = "point",colour = "darkred", size=4) +
     stat_summary(fun.data = meanFunction, geom ="text", color = "white", size = 3, vjust = 1.3)

df <- ggplot_build(g)$data[[1]] %>%
       select(ymin:ymax, x) %>%
       gather(type, value, - x) %>%
       arrange(x)

g + annotate("text", x = df$x + 0.4, y = df$value, label = df$value, size = 3)

这篇关于Boxplot上的全文标签,并添加了均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆