【问题标题】:plot geom_point on top of geom_histogram在 geom_histogram 上绘制 geom_point
【发布时间】:2019-12-12 02:59:58
【问题描述】:

我有一个数据框:

test <- structure(list(Sample_ID = c("S1","S2", "S3", "S4", "S1", "S2", "S3", "S4"), 
                       CN_Region = c("A", "A", "A", "A", "B", "B", "B", "B"),
                       MedianLog2Ratio = c(-0.2, -0.2, -0.25, -0.25, -0.25, -0.2, -0.1, -0.3), 
             CN_truth = c("2", "2", "2", NA, "2", "2", "2", "1")), class = c("data.table","data.frame"))

当我绘制hist 时,它工作正常: hist(test$MedianLog2Ratio)

我想使用 ggplot 绘制每个区域的直方图,并使用与 SampleID 关联的 geom_points CN_truth 叠加:

g <- ggplot(test, aes(x = MedianLog2Ratio)) + geom_histogram()
g + geom_point(aes(colour = factor(CN_truth))

情节应该看起来像这样松散的(当然它会有更少的数据块和更少的数据): 其中图例指的是CN_truth,标题是CN_Region

【问题讨论】:

  • 你的geom_pointy 是什么?
  • Y = 0,只想以 0/1 频率绘制它

标签: r ggplot2 plot


【解决方案1】:

一种方法如下:

test <- data.frame(Sample_ID = c("S1","S2", "S3", "S4", "S1", "S2", "S3", "S4"), 
                       CN_Region = c("A", "A", "A", "A", "B", "B", "B", "B"),
                       MedianLog2Ratio = c(-0.2, -0.2, -0.25, -0.25, -0.25, -0.2, -0.1, -0.3), 
                       CN_truth = c("2", "2", "2", NA, "2", "2", "2", "1"))
test <- transform(test, freqmlr = ave(seq(nrow(test)), MedianLog2Ratio, FUN=length))



g <- ggplot(test, aes(x = MedianLog2Ratio)) + geom_histogram(color="black", fill="white")+
     geom_point(aes(x=MedianLog2Ratio, y=freqmlr, colour=factor(CN_truth)))+
        xlab('MedianLog2Ratio') +
        ylab('Freq')+
        labs(colour='CN_truth')
g 

如果您想从图例中删除 NA(例如 this 一个),有很多帖子适合您。另请注意,如果 x 轴有许多具有相同值的点,您可以在每个直方图中稍微移动它们以使它们可见。例如通过添加随机十进制值:

g <- ggplot(test, aes(x = MedianLog2Ratio)) + geom_histogram(color="black", fill="white")+
  geom_point(aes(x=(MedianLog2Ratio+runif(nrow(test), 0.0, 0.010)), y=freqmlr, 
                 colour=CN_truth ))+
  xlab('MedianLog2Ratio') +
  ylab('Freq')+
  labs(colour='CN_truth')
g  + scale_colour_manual(values = c("red", "blue"), limits = c("1", "2")) 

【讨论】:

  • 感谢您的回答。有没有办法不绘制 NA?我也想为每个地区制作一个单独的情节。谢谢
  • 不用担心。请看上面,我对你问题的回答的第二部分。
  • 嗨,我不想仅仅从图例中排除 NA。我根本不想为 NA 绘制 geom_points。到目前为止,我有:` test$temp
  • 首先,您在第一次发布问题时必须非常具体。在 cmets 中添加修订并不是真正正确的方法。其次,这不是在绘图上绘制NA 值。如果您足够注意,最后会有一条警告说 Removed 1 rows containing missing values (geom_point). 最后,请记住,该行在被删除之前的频率仍然是算了。如果您想在计算频率之前删除 NA 行(我猜您不应该这样做),您可以在开始时使用 na.omit(test) 尽早排除 NA 行。
猜你喜欢
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2013-01-03
相关资源
最近更新 更多