Alex
Alex

Reputation: 540

ggplot2 change color of line based on categorical variable

I am looking for a way to have one consistent line across a date range that changes colors based on a categorical variable.

Let's say the data looks like this:

Date Value Category
1/1/14 - 10 - A
1/2/14 - 11 - A
1/3/14 - 20 - B
1/4/14 - 26 - B
1/5/14 - 50 - D

I would like the line to change colors as it passes through the different categories. Is there a way to do this with ggplot2? Or will I need to use a different library.

I can get the line graph, but it is broken and disjointed. enter image description here

Update
Currently I can get a scatterplot to do what I want with

qplot(x=data1$date, y = data1$value,data = data1, color = data1$category,geom="point")

However when I use "line" it tells me that

Each group consist of only one observation. Do you need to adjust the group aesthetic?

Upvotes: 2

Views: 6041

Answers (1)

user20650
user20650

Reputation: 25914

You need to assign a group variable:

using qplot:

  qplot(x=Date, y = Value,data = df, color = Category,group=1,geom="line")

or ggplot:

ggplot(df , aes(Date , Value , colour=Category , group=1)) + geom_line() 

Also note, in your qplot statement you do not need to use 'yourdata$' as you define the data = yourdata. If you use yourdata$var you will have problems using ggplot.

Upvotes: 4

Related Questions