ggplot散点图和线条

时间:2018-03-21 09:53:46

标签: r ggplot2 scatter-plot

我有两个人的生物学数据,我用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)

(我也想把水平蓝线和红线paralllel加到蓝线上)

请帮助!!!

非常感谢。

1 个答案:

答案 0 :(得分:2)

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

# 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()的水平线:< / p>

# 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。

相关问题