r - ggplot 散点图和线条

标签 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)

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

请帮忙!!!

非常感谢。

最佳答案

您可以在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添加水平线():

# 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于2018年3月21日创建(v0.2.0)。

关于r - ggplot 散点图和线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403058/

相关文章:

r - geom_bar() : stacked and dodged combined

pdf - 在R中使用工具提示创建pdf

r - 无需循环即可将向量转换为矩阵

从 ggplot 中删除 y 标签

r - 从点到原点的 ggplot 线和余弦分数

python - 如何在Google Colaboratory中旋转3D散点图?

javascript - 使用 HTML 和 Javascript 的散点图(使 y 轴从零开始(上下颠倒))

R Shiny Dashboard - 相当于navbarPage?

r - 我如何将所有不同的条目分类为男性、女性和非二元

r - 如何将我的散点图转换为正确的散点图?