JACKY88
JACKY88

Reputation: 3557

Plot points and lines on the same plot with ggplot2

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:

  1. How do I make the legend appear?
  2. I am new to ggplot2. I believe there must be an easier way to do this. Please show me. Thanks.

enter image description here

Upvotes: 0

Views: 1682

Answers (1)

bVa
bVa

Reputation: 3938

You need to use melt function from reshape2 to do this easily with ggplot2:

enter image description here

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: enter image description here

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

Related Questions