如何在R中绘制多条线

11

我有一些数据长这样:

#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

我想根据True(Y轴)和False(X轴)来绘制它们。

这大致是我想要它出现的样子。 This is the way I want it to appear roughly

该怎么做呢? 我的下面的代码失败了。

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]);
}
2个回答

7

由于您的数据已经是长格式,并且我喜欢ggplot图形,所以建议使用这种方法。读入数据后(请注意TRUEFALSE不是有效的名称,因此R会在列名后添加一个.),可以使用以下代码:

require(ggplot2)
ggplot(dat, aes(FALSE., TRUE., colour = as.factor(d), group = as.factor(d))) + 
  geom_line()
ggplot2网站上有许多有用的技巧。此外,注意这个SO搜索查询,其中包含许多与相关主题有关的其他好技巧。 enter image description here 就记录而言,以下是我修改您原始代码的方法:
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)

enter image description here


读取数据后,出现了以下错误:在eval(expr, envir, enclos)中发现对象'FALSE.'不存在。谢谢。 - neversaint
1
@neversaint - 我猜测R语言出现问题是因为TRUE和FALSE是R语言中的保留字。将你的列名更改为类似T和F的名称,一切都应该没问题了。我甚至不应该尝试使用这些名称来组合示例...这只会给你带来麻烦。colnames()是你需要的函数。 - Chase

6
这里提供一种基本的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被接受,但这可能仍然不是最好的编码实践。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接