Search code examples
rdataframeplotline-plot

How ro draw a multiline plot in R


I have a dataframe with 6 features like this:

                X1   X2   X3   X4   X5   X6
Modern Dog     9.7 21.0 19.4  7.7 32.0 36.5
Golden Jackal  8.1 16.7 18.3  7.0 30.3 32.9
Chinese Wolf  13.5 27.3 26.8 10.6 41.9 48.1
Indian Wolf   11.5 24.3 24.5  9.3 40.0 44.6
Cuon          10.7 23.5 21.4  8.5 28.8 37.6
Dingo          9.6 22.6 21.1  8.3 34.4 43.1 

I want to draw a line plot like this:

enter image description here

I'm trying this:

plot(df$X1, type = "o",col = "red", xlab = "Month", ylab = "Rain fall")

lines(c(df$X2, df$X3, df$X4, df$X5, df$X6), type = "o", col = "blue")

But it's only plotting a single variable. I'm sorry if this question is annoying, i'm totally new to R and i just don't know how to get this done. I would really appreciate any help on this.

Thanks in advance


Solution

  • The easiest way would be to convert your dataset to a long format (e.g. by using the gather function in the tidyr package), and then plotting using the group aesthetic in ggplot.

    I recreate your dataset, assuming your group variable is named "Group":

    df <- read.table(text = "
    Group                X1   X2   X3   X4   X5   X6
    Modern_Dog     9.7 21.0 19.4  7.7 32.0 36.5
    Golden_Jackal  8.1 16.7 18.3  7.0 30.3 32.9
    Chinese_Wolf  13.5 27.3 26.8 10.6 41.9 48.1
    Indian_Wolf   11.5 24.3 24.5  9.3 40.0 44.6
    Cuon          10.7 23.5 21.4  8.5 28.8 37.6
    Dingo          9.6 22.6 21.1  8.3 34.4 43.1 ",
      header = TRUE, stringsAsFactors = FALSE)
    

    Then convert the dataset to long format and plot:

    library(tidyr)
    library(ggplot2)
    
    df_long <- df %>% gather(X1:X6, key = "Month", value = "Rainfall")
    ggplot(df_long, aes(x = Month, y = Rainfall, group = Group, shape = Group)) +
      geom_line() +
      geom_point() +
      theme(legend.position = "bottom")
    

    enter image description here

    See also the answers here: Group data and plot multiple lines.