ggplot 散点图和线条

ggplot scatterplot and lines

我有两个人的一些生物数据,我使用 R 作为散点图使用 ggplot 绘制它,如下所示:

p1<-ggplot(data, aes(meth_matrix$sample1, meth_matrix$sample3)) +
  geom_point() +
  theme_minimal()

效果很好,但我想添加线条:将散点图分成两半的 abline:

p1  + geom_abline(color="blue")

我的问题是:如何绘制两条平行于对角线的红线(y 截距为 0.2,斜率与蓝线相同)??

此外:如何使用 ggplot 在类似的散点图中(看起来像水平散点图)绘制两个样本的差异?现在我只能用这样的情节来做:

dif_samples<-meth_matrix$sample1- meth_matrix$sample3
plot(dif_samples, main="difference", 
     xlab="CpGs ", ylab="Methylation ", pch=19)

(我还想添加水平蓝线和与蓝线平行的红线)

请帮忙!!!

非常感谢。

您可以在 geom_abline() 函数中指定斜率和截距。我将使用ggplot2自带的鸢尾花数据集来说明:

# I'll use the iris dataset. I normalise by dividing the variables by their max so that
# a line through the origin will be visible
library(ggplot2)
p1 <- ggplot(iris, aes(Sepal.Length/max(Sepal.Length), Sepal.Width/max(Sepal.Width))) + 
  geom_point() + theme_minimal()

# Draw lines by specifying their slopes and intercepts. since all lines
# share a slope I just give one insted of a vector of slopes
p1 + geom_abline(intercept = c(0, .2, -.2), slope = 1,  
                 color = c("blue", "red", "red"))

我不太清楚你想要的第二个情节,但你可以直接在 ggplot() 的调用中绘制差异,你可以用 geom_hline() 添加水平线:

# Now lets plot the difference between sepal length and width
# for each observation

p2 <- ggplot(iris, aes(x = 1:nrow(iris), 
                       y = (Sepal.Length - Sepal.Width) )) + 
  geom_point() + theme_minimal()

# we'll add horizontal lines -- you can pick values that make sense for your problem
p2 + geom_hline(yintercept = c(3, 3.2, 2.8),  
                 color = c("blue", "red", "red"))

reprex package (v0.2.0) 创建于 2018-03-21。