Search code examples
rplotline-plot

Plotting two sets of lines from two categories (e.g. colour)


I want to make a line graph of 2 sets of lines across 4 points, with the lines being differentiated by colour (Black or Gray50). The black and gray lines should not be connected.

My dataframe looks like this:

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

My code so far:

#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.

Anybody know how I can get it so that each line is only 4 points long going in order in the file and according to colour? Any help is GREATLY appreciated!


Solution

  • In the following, I am just running a loop to get each four lines. I am not sure if this is what you are after...

    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