Reputation: 3557
I want to plot two scatter plots with lines on the same plot using ggplot2
. I also want to specify the colors.
dat <- data.frame(x = 1:10, y1 = 2:11, y2 = 3:12)
ggplot(dat, aes(x)) + geom_line(aes(y = y1, color = "y1"), color = "blue") + geom_line(aes(y = y2, color = "y2"), color = "red") + geom_point(aes(y = y1), color = "blue") + geom_point(aes(y = y2), color = "red")
Two questions:
Upvotes: 0
Views: 1682
Reputation: 3938
You need to use melt
function from reshape2
to do this easily with ggplot2
:
dat <- data.frame(x = 1:10, y1 = 2:11, y2 = 3:12)
library(reshape2)
dat.melt = melt(dat, id = "x")
> print(dat.melt)
x variable value
1 1 y1 2
2 2 y1 3
3 3 y1 4
4 4 y1 5
5 5 y1 6
6 6 y1 7
7 7 y1 8
8 8 y1 9
9 9 y1 10
10 10 y1 11
11 1 y2 3
12 2 y2 4
13 3 y2 5
14 4 y2 6
15 5 y2 7
16 6 y2 8
17 7 y2 9
18 8 y2 10
19 9 y2 11
20 10 y2 12
ggplot(dat.melt, aes(x = x, y = value, color = variable)) + geom_line() + geom_point()
EDIT
Add + scale_color_manual
to manually set the colors:
ggplot(dat.melt, aes(x = x, y = value, color = variable)) + geom_line() + geom_point() +
scale_color_manual("legend", values = c("y1" = "darkgreen", "y2" = "purple"))
Upvotes: 1