I need to create a simple line plot with groups using the following data:
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1","Group 2"),3),
groupcd= rep(c(1,2),3),
y= c(22,8,11,4,7,5)
)
I can easily do it with GGPLOT:
library(ggplot2)
#GGPLOT
qplot(x=x, y=y,
data=test,
colour=group,
main="GGPLOT line plot with groups") +
geom_line()
I can also do it with TRELLIS:
library(lattice)
xyplot(y~x,
type="b",
group=group,
data=test,
main="TRELLIS line plot with groups",
auto.key =list(
lines = TRUE)
)
However, I am a bit reluctant to use GGPLOT or TRELLIS right now. I'd like to be able to create this graph with Base R. The only way I can get this plot to work in Base R is by using for loop:
# set up empty plot
plot(test$y ~test$x, ylab="y", xlab="x", type="n", main="Base R line plot with groups")
colors<-c("red","blue")
#plot each group in the for loop
number_of_groups <- as.numeric(max(unique(test$groupcd))) #calculate number of groups
for (i in 1:number_of_groups)
{
temp <- subset(test, groupcd==i )
lines(temp$x, temp$y, col=colors[i])
points(temp$x, temp$y, col=colors[i])
}
legend("top", legend=unique(test$group), text.col =colors )
This approach seems quite convoluted. Is there an easier way to do it in base R? Is there a group option in base R plot function? Thank you so much.
The basic plot command Here, we use type="l" to plot a line rather than symbols, change the color to green, make the line width be 5, specify different labels for the x and y axis, and add a title (with the main argument).
To create a line plot, first create a number line that includes all the values in the data set. Next, place an X (or dot) above each data value on the number line. If a value occurs more than once in a data set, place an Xs over that number for each time it occurs.
Different approach using MATPLOT:
library(reshape)
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1","Group 2"),3),
groupcd= rep(c(1,2),3),
y= c(22,8,11,4,7,5)
)
colors<-c("red","blue")
#Transform data to wide format
test_transposed<-reshape(test,
idvar='x',
drop="group",
timevar="groupcd",
direction="wide")
colors<-c("red","blue")
#drop x column
test_transposed$x<-NULL
matplot(test_transposed,
type = "b",
ylab="y",
col=colors,
main="MATPLOT with groups",
pch = 1:2)
legend("top",
legend=unique(test$group),
lty=1:2,
col=colors,
pch=1:2 )
What about something like this as a base to work from:
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1", "Group 2"), 3),
group_cd = rep(c(1, 2), 3),
y = c(22, 8, 11, 4, 7, 5))
xvals <- split(test$x, test$group)
yvals <- split(test$y, test$group)
plot(1:max(unlist(xvals)), ylim = c(0, max(unlist(yvals))), type = "n")
# thanks to @BenBolker for refining this next key line
mapply(lines, xvals, yvals, col = c("red", "blue"), pch = 1:2, type = "o")
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With