分组数据并绘制多行 [英] Group data and plot multiple lines

查看:113
本文介绍了分组数据并绘制多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中为这个数据集绘制多行:(x = Year,y = Value)

  School_ID年份价值
A 1998 5
B 1998 10
C 1999 15
A 2000 7
B 2005 15

每所学校都有不同年份的数据。我想每个学校都有一行。

我们创建一些数据:

  dd = data.frame(School_ID = c(A,B,C,A,B),
年= c(1998年,1998年,1999年,2000年,2005年),
价值= c(5,10,15,7,15))

然后在基本图形中创建一个图形,我们创建一个初始图形组:

  plot(dd $ Year [dd $ School_ID ==A],dd $ Value [dd $ School_ID ==A],type =b,
xlim = range dd $ Year),ylim = range(dd $ Value))

然后迭代添加行:

 行(dd $ Year [dd $ School_ID ==B],dd $ Value [dd $ School_ID == B'],col = 2,type =b)
lines(dd $ Year [dd $ School_ID ==C],dd $ Value [dd $ School_ID ==C],col = 3,type =b)

我已经使用 type = b来显示点和线。



或者,使用ggplot2:

 require(ggplot2)
##数值Year,Value,School_ID是
##由geoms继承
ggplot(dd,aes(Year,价值,颜色= School_ID))+
geom_line()+
geom_point()


I'd like to plot multiple lines in R for this dataset: (x = Year, y = Value)

School_ID   Year    Value
A           1998    5
B           1998    10
C           1999    15
A           2000    7
B           2005    15

Each school has data for different years. I'd like to have one line for each school.

解决方案

Let's create some data:

dd = data.frame(School_ID = c("A", "B", "C", "A", "B"),
  Year = c(1998, 1998, 1999, 2000, 2005),
  Value = c(5, 10, 15, 7, 15))

Then to create a plot in base graphics, we create an initial plot of one group:

plot(dd$Year[dd$School_ID=="A"], dd$Value[dd$School_ID=="A"], type="b",
     xlim=range(dd$Year), ylim=range(dd$Value))

then iteratively add on the lines:

lines(dd$Year[dd$School_ID=="B"], dd$Value[dd$School_ID=="B"], col=2, type="b")
lines(dd$Year[dd$School_ID=="C"], dd$Value[dd$School_ID=="C"], col=3, type="b")

I've used type="b" to show the points and the lines.

Alternatively, using ggplot2:

require(ggplot2)
##The values Year, Value, School_ID are
##inherited by the geoms
ggplot(dd, aes(Year, Value,colour=School_ID)) + 
    geom_line() + 
    geom_point()

这篇关于分组数据并绘制多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆