如何在R中绘制多条直线

如何在R中绘制多条直线,r,plot,R,Plot,我的数据如下所示: #d TRUE FALSE Cutoff 4 28198 0 0.1 4 28198 0 0.2 4 28198 0 0.3 4 28198 13 0.4 4 28251 611 0.5 4 28251 611 0.6 4 28251 611 0.7 4 28251 611 0.8 4 28251 611 0.9 4 28251 611 1 6 19630 0

我的数据如下所示:

#d  TRUE    FALSE   Cutoff
4   28198   0   0.1
4   28198   0   0.2
4   28198   0   0.3
4   28198   13  0.4
4   28251   611 0.5
4   28251   611 0.6
4   28251   611 0.7
4   28251   611 0.8
4   28251   611 0.9
4   28251   611 1
6   19630   0   0
6   19630   0   0.1
6   19630   0   0.2
6   19630   0   0.3
6   19630   0   0.4
6   19636   56  0.5
6   19636   56  0.6
6   19636   56  0.7
6   19636   56  0.8
6   19636   56  0.9
6   19636   56  1
所以我想根据真(Y轴)和假(X轴)绘制它们

这是我希望它大致呈现的方式。

正确的方法是什么? 我下面的代码失败了

dat<-read.table("mydat.txt", header=F);
dis     <- c(4,6);
linecols <-c("red","blue");
plot(dat$V2 ~ dat$V3, data = dat,  xlim = c(0,611),ylim =c(0,28251), type="l")

for (i in 1:length(dis)){
datax <- subset(dat, dat$V1==dis[i], select = c(dat$V2,dat$V3))
lines(datax,lty=1,type="l",col=linecols[i]);
}

dat由于您的数据已经是长格式的,而且我还是喜欢ggplot图形,所以我建议使用该路径。在中读取数据后(请注意,
TRUE
FALSE
不是有效名称,因此R在列名后附加了一个
),以下操作应有效:

require(ggplot2)
ggplot(dat, aes(FALSE., TRUE., colour = as.factor(d), group = as.factor(d))) + 
  geom_line()
网站上有很多好的提示。还请注意许多其他有关相关主题的好提示

作为记录,以下是我如何处理修改原始代码时遇到的问题:

colnames(dat)[2:3] <- c("T", "F")

dis <- unique(dat$d)

plot(NA, xlim = c(0, max(dat$F)), ylim = c(0, max(dat$T)))
for (i in seq_along(dis)){
  subdat <- subset(dat, d == dis[i])
  with(subdat, lines(F,T, col = linecols[i]))
}
legend("bottomright", legend=dis, fill=linecols)

colnames(dat)[2:3]这里有一个基本的R方法,假设您的数据在本例中被称为
dat

plot(1:max(dat$false), xlim = c(0,611),ylim =c(19000,28251), type="n")

apply(
rbind(unique(dat$d),1:2),
#the 1:2 here are your chosen colours
2,
function(x) lines(dat$false[dat$d==x[1]],dat$true[dat$d==x[1]],col=x[2])
)
结果:


编辑-虽然可以接受对变量名使用小写的true/false,但这可能仍然不是最好的编码实践。

谢谢。在读取数据之后。它给了我这个错误:eval(expr,envir,enclose)中的错误:对象'FALSE'。找不到。@neversaint-我猜R有问题,因为TRUE和FALSE是R中的保留字。将列名更改为类似于T和F的内容,一切都应该正常。我甚至不应该把这个例子和那些名字放在一起……这只会给你的朋友带来麻烦
colnames()
是您需要的函数。