Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot创建相关图_R_Ggplot2 - Fatal编程技术网

R ggplot创建相关图

R ggplot创建相关图,r,ggplot2,R,Ggplot2,我正在尝试使用ggplot2创建to变量之间的线性相关图: dput(sum) structure(list(Date = structure(c(15218, 15248, 15279, 15309, 15340, 15371, 15400, 15431, 15461, 15492, 15522, 15553), class = "Date"), Teams = c(87, 142, 173, 85, 76, 76, 93, 49, 169, 139, 60, 120),

我正在尝试使用
ggplot2
创建to变量之间的线性相关图:

dput(sum)
structure(list(Date = structure(c(15218, 15248, 15279, 15309, 
15340, 15371, 15400, 15431, 15461, 15492, 15522, 15553), class = "Date"), 
    Teams = c(87, 142, 173, 85, 76, 76, 93, 49, 169, 139, 60, 
    120), Scores = c("67101651", "62214988", "63183320", "66750198", 
    "61483322", "67546775", "75290893", "60713372", "77879142", 
    "70290302", "83201853", "83837301")), .Names = c("Date", 
"Teams", "Scores"), row.names = c(NA, 12L), class = "data.frame")
这是我的命令:

ggplot(sum, aes(x = Scores, y = Teams, group=1)) + 
    geom_smooth(method = "lm", se=TRUE, size=2, formula = lm(Teams ~ Scores))
我得到这个错误:

Error in eval(expr, envir, enclos) : object 'Teams' not found

有什么想法吗?

如果您想指定线性模型等的公式,请使用
y~多边形(x,1)
。只要您想要一个简单的线性回归(这是
method=“lm”
)的默认值),就不需要更改
公式
参数:

如果您不希望此变量是分类变量,我还建议您使用
分数
作为数值(
作为.numeric(分数)
)。这将改变回归线

得分
作为分类变量:

分数
作为数字变量:


这里有另一个选项,使用
ggpubr
包中的
stat\u cor
。此代码将绘制点并显示相关性和p值。如果您有非正常数据,可以将“皮尔逊”改为“斯皮尔曼”

ggplot(sum, aes(x = Scores, y = Teams, group = 1)) +
  geom_point(aes()) +
  geom_smooth(method = "lm", se = TRUE, size = 2) +
  stat_cor(method = "pearson", cor.coef.name = "r", vjust = 1, size = 4)

是否有一种简单的方法将r平方值打印为图例?一种简单的方法是将其打印在标题中。只需将
opts(title=bquote(R^2~”:“~(summary(lm(Teams~as.numeric(Scores),sum))$R.squared)添加到绘图中即可。
对于该线程的任何未来读者来说,像最常用的基本R函数之一那样调用数据帧都不是一个好主意。在这种情况下,请允许我提醒您,
df
也是一个基本的R函数(尽管使用频率比
sum
低),这是否回答了您的问题?
ggplot(sum, aes(x = Scores, y = Teams, group = 1)) +
  geom_point(aes()) +
  geom_smooth(method = "lm", se = TRUE, size = 2) +
  stat_cor(method = "pearson", cor.coef.name = "r", vjust = 1, size = 4)