我想在R中为此数据集绘制多条线:(x =年,y =值)
School_ID Year Value
A 1998 5
B 1998 10
C 1999 15
A 2000 7
B 2005 15
每所学校都有不同年份的数据。我希望每所学校都有一行。
答案 0 :(得分:28)
让我们创建一些数据:
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))
然后,要在基础图形中创建一个图,我们创建一个组的初始图:
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"
来显示点和线。
另外,使用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()
答案 1 :(得分:14)
group = School_id
告诉ggplot2为每所学校绘制单独的行。如果您希望横轴包含1998年到2005年之间的所有年份,请删除factor
中的x = factor(year)
library(ggplot2)
df = read.table(text = "School_id Year Value
A 1998 5
B 1998 10
C 1999 15
A 2000 7
B 2005 15", sep = "", header = TRUE)
ggplot(data = df, aes(x = factor(Year), y = Value, color = School_id)) +
geom_line(aes(group = School_id)) + geom_point()
答案 2 :(得分:4)
基础R中的绘图功能不支持分组,因此您需要逐个显示您的组。 GGPLOT很好地处理分组。我还建议您查看Trellis XYPLOT,它允许您绘制单独的组。
这是使用Trellis创建基本分组线图的方法:
library(lattice)
rm(list = ls()) # clear objects
graphics.off() # close graphics windows
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1","Group 2"),3),
y= c(22,8,11,4,7,5)
)
xyplot(y~x,
type="b",
group=group,
data=test,
auto.key =list(
points = FALSE,
columns=2,
lines = TRUE)
)