【问题标题】:Create line and curve line user defined values创建直线和曲线用户定义值
【发布时间】:2021-07-06 03:29:13
【问题描述】:

您好,我有一个平滑的散点图,我想用 ggplot 尝试使用相同的图,任何人都可以帮助我使用 ggplot 创建图,但无法创建与平滑散点图相同的曲线和对角线

数据

   A    B   cat
0.8803  0.0342  data1
0.9174  0.0331  data1
0.9083  0.05    data1
0.7542  0.161   data2
0.8983  0.0593  data2
0.8182  0.1074  data2
0.3525  0.3525  data3
0.5339  0.2288  data3
0.7295  0.082   data3

平滑散点图

df=read.table("test.txt", sep='\t', header=TRUE)
smoothScatter(df$B,df$A,,nrpoints=Inf,xlim=c(0,1),ylim=c(0,1), pch=20,cex=1, col=df$cat)
points(c(0,1),c(1,0),type='l',col='green',lty=2,lwd=2)
p=0:1000/1000
points((1-p)^2,p^2,type='l',col='red',lty=2,lwd=2)

ggplot 脚本

ggplot(df, aes(x=B, y=A))+
  geom_point()

【问题讨论】:

  • 请为您的数据(df 对象)提供可重现的代码。您可以通过粘贴 dput(df) 的输出来做到这一点。也就是说,您应该看到,对于每个图像“对象”(线条、点等几何图形),您应该添加一个几何图形,包括 geom_smooth()geom_line() 等等。关于如何在ggplot中制作smoothScatter,这里可能有答案:stackoverflow.com/questions/13094827/…

标签: r ggplot2 scatter-plot


【解决方案1】:

如果您尝试根据方程式绘制线条,您可以定义方程式,然后使用geom_linestat="function" 绘制该线条。以下是在ggplot 中绘制线条并模拟相同外观的方法:

library(ggplot2)

curvy <- function(x) { ((1-x)^2)^2 }
straight <- function(x) 1-x

ggplot(df, aes(x=B, y=A))+
  geom_point(size=3) +
  geom_line(stat='function', fun=straight, color='green', linetype='dashed', size=1) +
  geom_line(stat='function', fun=curvy, color='red', linetype='dashed', size=1) +
  xlim(0,1) + ylim(0,1) +
  theme_classic()

至于模糊点,可以给ggblur一试here's the github。它不适用于我正在使用的版本。

通过回归在绘图上绘制线条的另一种方法是使用geom_smooth()。您需要在此处指定method - 对于线性,您可以使用"lm" - 默认使用"loess"

ggplot(df, aes(x=B, y=A))+
  geom_point(size=3) +
  geom_line(stat='function', fun=straight, color='green', linetype='dashed', size=1) +
  geom_line(stat='function', fun=curvy, color='red', linetype='dashed', size=1) +
  geom_smooth(method='lm', alpha=0.2, color='blue', fill='skyblue', linetype='dotted') +
  xlim(0,1) + ylim(0,1) +
  theme_classic()

【讨论】:

  • 谢谢,但你给的曲线很漂亮curvy &lt;- function(x) { ((1-x)^2)^2 }points((1-p)^2,p^2,type='l',col='red',lty=2,lwd=2) 不一样
  • 我重新编辑了我的问题,粘贴了它的样子
猜你喜欢
  • 2013-05-30
  • 2015-10-20
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多