简体   繁体   English

如何使用 ggplot2 在一个散点 plot 上的 x 轴上 plot 多列?

[英]How to plot multiple columns on the x axes on one scatter plot using ggplot2?

I am new to coding and to R and I have this data set that I would like to scatter plot with a line using the ggplot2 package. I am new to coding and to R and I have this data set that I would like to scatter plot with a line using the ggplot2 package. Basically, I want to show the number of tests for each grade (G3-G8) by year.基本上,我想按年份显示每个年级(G3-G8)的测试次数。 I want all the grades on the "x" axes and the year on the "y" axes.我想要“x”轴上的所有成绩和“y”轴上的年份。 I tried (tidyr/gather) and (reshape2/ melt) but I keep getting an error message.我尝试了 (tidyr/gather) 和 (reshape2/melt) 但我不断收到错误消息。

Year    G3  G4  G5  G6  G7  G8
2003    6   10  8   4   6   8
2004    10  12  4   12  19  10
2005    11  9   13  10  13  11
2006    26  25  28  37  32  19
2007    5   1   3   4   3   1
2008    4   2   4   4   4   2
2009    6   4   8   8   8   6
2010    5   5   5   5   5   5
2011    8   8   8   8   8   8
2012    6   6   6   6   6   6
2013    3   3   3   3   3   3
2014    5   4   4   4   4   4
2015    60  60  60  60  60  60
2016    26  26  26  26  26  26
2017    6   6   6   6   6   6
2018    18  18  18  18  18  18

Here's an approach with pivot_longer from the tidyr package.这是tidyr package 中使用pivot_longer的方法。

There is a slight disconnected between what you say in the first sentence "I want to show the number of tests for each grade (G3-G8) by year", and then your variable mapping in the next sentence.您在第一句话中所说的“我想按年份显示每个年级(G3-G8)的测试次数”与下一句中的变量映射之间略有脱节。 But perhaps you can edit it from here if this is not what you want.但如果这不是您想要的,也许您可以从这里编辑它。

library(tidyr)
library(ggplot2)
data %>%
  pivot_longer(-Year,names_to = "Grade", values_to = "NumberTests") %>%
ggplot(aes(x = Year, y = NumberTests, color = Grade)) +
  geom_line() + 
  geom_point()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM