Jimmy
Jimmy

Reputation: 427

How to use ggplot2 to plot lines with category variable?

I have a data frame, I've used geom_line from ggplot2 to draw a line (see picture 1).

data = read.csv('data.csv')
ggplot() + geom_line(aes(x=1:10,y=data$FA[1:10]),size=I(1.5))

    FA      FT
1   1.07644  0
2   1.07611  0
3   1.07462  1
4   1.07328  0
5   1.06994  0
6   1.07026  1
7   1.06879  0
8   1.06815  1
9   1.06979  0
10  1.07243  1

How do I add another line where FT == 1 to the existing plot so it will look something the the second picture?
(connect the points where FT == 1)

enter image description here

enter image description here

Upvotes: 2

Views: 59

Answers (1)

erc
erc

Reputation: 10131

You can add a line grouped by FT and set the colour of the line with FT == 0 to NA.

ggplot(dat) + 
  geom_line(aes(x = 1:10,y = FA[1:10]), size = I(1.5)) +
  geom_line(aes(x = 1:10,y = FA[1:10], group = FT, colour = factor(FT)), size = I(1.5), show.legend = FALSE) +
  scale_colour_manual(values = c(NA, "red"))

enter image description here

Upvotes: 3

Related Questions