-2

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!

Jaap
  • 55
  • 1
  • 2
  • 5
  • Hi Jaap. If you want to improve your question, here is some information on [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [minimale reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). The MRE will make it easier for others to find and test a answer to your question. That way you can help others to help you! – dario Feb 11 '21 at 15:21

1 Answers1

2

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])
}