Search code examples
rggplot2line

How to create a graph (ggplot)f rom data in multiple columns


I know how to create a graph using data from 1 column, but how do I create a line graph from a df containing multiple columns, having one line per column?

looking like: x-axis = age and y = n

sample dataset:

DF <- data.frame(age = c('0-20', '21-30', '31-40'), q1_10 = c(3,2,1), q1_11 = c(4,5,6), q1_12 = c(5,3,1))

ty!


Solution

  • I suggest base R plotting. Your dataset:

    DF <- data.frame(age   = c('0-20', '21-30', '31-40'), 
                     q1_10 = c(3,2,1),
                     q1_11 = c(4,5,6), 
                     q1_12 = c(5,3,1))
    

    Extract your data:

    data <- matrix(unlist(DF[-1]),3,3)
    labels <- unlist(DF[1])
    

    Plot:

    ### creating an empty plot
    plot(1:3,type="n",ylim=c(min(data),max(data)),xlab="age",ylab="n",xaxt="n")
    
    ### creating the x axis
    axis(1,1:3,labels=labels)
    
    ### plot the lines
    for(i in 1:3){
      lines(1:3,data[,i])
    }