如何根据多列数据创建图表 (ggplot)

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

我知道如何使用 1 列的数据创建图表,但我如何从包含多列的 df 创建折线图,每列有一条线?

看起来像:x 轴 = 年龄和 y = n

示例数据集:

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

好吧!

我建议使用 base R 绘图。您的数据集:

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

提取您的数据:

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

剧情:

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