【问题标题】:Add median value for each boxplot为每个箱线图添加中值
【发布时间】:2018-07-10 09:04:26
【问题描述】:

这是文件 new.txt

Chr Start   End Name    18NGS31 18MPD168    18NGS21 18NGS29 18NGS33 18NGS38
chr9    1234    1234    ABL1    1431    1   1112    1082    1809    1647
chr9    2345    2345    ASXL1   3885    37  3578    1974    2921    3559
chr9    3456    3456    ETV6    3235    188 2911    1578    2344    2673
chr9    4567    4567    MYD88   3198    187 2860    1547    2289    2621

我正在使用 R 脚本从第 5 列开始制作箱线图

library(tidyverse)
file <- "new.txt"
df <- read.table(file, header = T, check.names=F)
a <-  df %>%
  gather(key, value, -Chr, -Start, -End, -Name) %>%
  ggplot(aes(x = key, y = value )) +
  geom_boxplot(fill = "orange", colour = "firebrick2") + scale_y_continuous(name="Coverage", limits=c(0, 5000), breaks = seq(0,5000,by = 500)) + scale_x_discrete(name='Samle ID')
a + theme(axis.text.x = element_text(angle = 90, hjust = 1))

我想添加每个箱线图的中值。

我使用了来自How to display the median value in a boxplot in ggplot?的ggplot的geom_text

但我做不到。

这是我使用的命令

file <- "new.txt"
df <- read.table(file, header = T, check.names=F)
a <-  df %>%
  gather(key, value, -Chr, -Start, -End, -Name)
b <- ggplot(a,aes(x = key, y = value )) +
        geom_boxplot(fill = "orange", colour = "firebrick2") + scale_y_continuous(name="Coverage", limits=c(0, 5000), breaks = seq(0,5000,by = 500)) + scale_x_discrete(name='Samle ID')+
        geom_text(data=a,aes(x= key, y = median(value) , label =median(value)), position=position_dodge(width = 0.8),size = 3, vjust = -0.5,colour="blue")
b + theme(axis.text.x = element_text(angle = 90, hjust = 1))

这是输出

中值计算错误。

【问题讨论】:

  • 为什么你做不到?你能发布你得到的代码和结果/错误吗?

标签: r ggplot2 boxplot


【解决方案1】:

问题是您计算所有keymedian(当您使用median(value) 时得到2131 的数字)。您可以使用group_bykey 对记录进行分组,然后才计算中位数(dplyr 包中的summarise 函数):

library(tidyverse)
dataInput  <- gather(df, key, value, -Chr, -Start, -End, -Name)
dataMedian <- summarise(group_by(dataInput, key), MD = median(value))
ggplot(dataInput, aes(key, value)) +
    geom_boxplot() + 
    geom_text(data = dataMedian, aes(key, MD, label = MD), 
              position = position_dodge(width = 0.8), size = 3, vjust = -0.5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多