如何在R中绘制多条线 [英] How to plot multiple lines in R
问题描述
我有一个看起来像这样的数据:
I have a data that looks like this:
#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轴)绘制它们.
So I want to plot them based on True (Y-axis) and False (X-axis).
这是我希望它粗略显示的方式.
This is the way I want it to appear roughly.
什么是正确的方法? 我下面的代码失败
What's the right way to do it? My code below fails
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]);
}
推荐答案
由于您的数据已经是长格式,并且无论如何我都喜欢ggplot图形,因此建议您使用该路径.读入数据后(请注意TRUE
和FALSE
是无效名称,因此R在列名称后附加了.
),以下方法应该起作用:
Since your data is already in long format and I like ggplot graphics anyway, I'd suggest that path. After reading your data in (note that TRUE
and FALSE
are not valid names, so R appended a .
to the column names), the following should work:
require(ggplot2)
ggplot(dat, aes(FALSE., TRUE., colour = as.factor(d), group = as.factor(d))) +
geom_line()
ggplot2 网站上有很多不错的提示.另请注意有关SO的搜索查询,以获得许多其他与相关主题相关的好技巧
The ggplot2 website is full of good tips. Also note this search query on SO for lots of other good tips on related topics.
记录下来,这是我修改原始代码时遇到的问题的方法:
And for the record, here's how I'd approach your problem modifying your original code:
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)
这篇关于如何在R中绘制多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!