从两个类别(例如颜色)绘制两组线

时间:2017-12-08 03:13:28

标签: r plot line-plot

我想在4个点上制作2组线条的线图,线条按颜色区分(黑色或灰色50)。不应连接黑线和灰线。

我的数据框如下所示:

Index    Frequency Colour
1              1    Black
2              1    Black
3              0.8  Black
4              0    Black
1              0    Gray50
2              0    Gray50
3        0.88235294 Gray50
4              1    Gray50
1              1    Black
2              1    Black
3        0.85714286 Black
4              0    Black
1       0.02631579  Gray50
2         0.0625    Gray50
3          0.875    Gray50
4              1    Gray50
1              1    Black
2              1    Black
3             0.875 Black
4              0    Black
1              0    Gray50
2              0    Gray50
3        0.86666667 Gray50
4              1    Gray50 

Here is a rough example of the type of line graph I'd like

到目前为止我的代码:

#object made from dataframe
alleles <- parallel_allele_freq

##plot 

plot(alleles$Index,alleles$Frequency,xlab = "Gradient",xaxt = 'n',
     ylab = "Frequency of P allele",
     col = alleles$Colour, pch = 16, cex = 1.25, type = "b")

axis(1, at = seq(1, 4, by = 1))

And here is the graph I'm getting, with black and gray lines connected.

任何人都知道我怎么能得到它,以便每行只有4个点长的顺序在文件中并根据颜色? 非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

在下面,我只是运行一个循环来获取每四行。 我不确定这是不是你想要的......

x <- read.table("temp.txt", header = TRUE)
plot(x$Index[1:4], x$Frequency[1:4], col=tolower(x$Colour[1]), 
     type = "b", lwd = 2,
     xlab = "Gradient", xaxt = 'n',
     ylab = "Frequency of P allele",
     pch = 16, cex = 1.25)

for (j in 1:5)
  points(x$Index[(j*4)+1:4], x$Frequency[(j*4)+1:4], 
          col=tolower(x$Colour[(j*4)+1]),
          type = "b", lwd = 2)

axis(1, at = seq(1, 4, by = 1))

enter image description here