[英]Group data and plot multiple lines
I'd like to plot multiple lines in R for this dataset: (x = Year, y = Value) 我想在R中为这个数据集绘制多条线:(x =年,y =值)
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. 我用
type="b"
来显示点和线。
Alternatively , using ggplot2: 或者 ,使用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()
Is this what you want? 这是你想要的吗? You need
group = School_id
to tell ggplot2 to plot separate lines for each school. 你需要
group = School_id
来告诉ggplot2为每所学校绘制单独的行。 If you want the horizontal axis to incluude all years between 1998 and 2005, then remove factor
in x = factor(year)
如果你想要水平轴包括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()
The plot function in base R does not support grouping so you need to display your groups one by one. 基础R中的绘图功能不支持分组,因此您需要逐个显示您的组。 GGPLOT handles grouping well.
GGPLOT很好地处理分组。 I also suggest looking at Trellis XYPLOT which allows you to plot separate groups.
我还建议您查看Trellis XYPLOT,它允许您绘制单独的组。
This is how you can create a basic grouped line plot using Trellis: 这是使用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)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.