分组数据并绘制多条线 [英] Group data and plot multiple lines
本文介绍了分组数据并绘制多条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 R 中为此数据集绘制多行:(x = Year, y = Value)
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.
推荐答案
让我们创建一些数据:
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))
然后在行上迭代添加:
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")
我使用了 type="b"
来显示点和线.
I've used type="b"
to show the points and the lines.
或者,使用 ggplot2:
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屋!
查看全文