Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 multiple stat_smooth: change color & linetype

Tags:

r

ggplot2

I am not able to change the colors and linetypes of my current plot with multiple smoother ( stat_smooth())

Here an overview of the data structure:

     serviceInstanceName            timestamp     value
1    DE1Service-utilityPredicted    2014-02-22    10.000000
2    SE1Service-utilityPredicted    2014-02-22     4.385694
3    DE2Service-utilityPredicted    2014-02-22     0.000000
4    US1Service-utilityPredicted    2014-02-22     2.230000
5    DE1Service-utilityActual       2014-02-22    10.000000
6    SE1Service-utilityActual       2014-02-22     8.011919
7    DE2Service-utilityActual       2014-02-22     3.000000
8    US1Service-utilityActual       2014-02-22     1.325191
...

There are eight unique service instances with according timestamp (y axis) and value (x axis).

Here the code:

ggplot(rmm, aes(x=timestamp, y=value, color=serviceInstanceName, group=serviceInstanceName)) 
+ stat_smooth(size=1.5, method = "loess", level = 0.95, fullrange = TRUE, se = FALSE)
+ scale_x_datetime(breaks = date_breaks("1 day"), labels = date_format("%a/%m"))
+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) + xlab("Day") 
+ ylab("Utility") + ggtitle("Utility Trend")

Here the plot: http://imgur.com/Tk02YXC

What I want:

=> To manually change the linetypes and colors of each unique *serviceInstanceName' attribute value. I tried many things from scale_color_manual() .. until extracting the value of the smoother.. but really could not solve this.

Any help is appreciated. Thanks!

like image 306
philka Avatar asked Jul 18 '14 15:07

philka


1 Answers

Well, your data wasn't that hlpeful for recreating the plot so i created a different sample data set

rmm<-data.frame(
    timestamp = as.POSIXct(rep(seq(as.Date("2014-01-01"), 
        as.Date("2014-01-10"), by="1 day"),5)),
    serviceInstanceName = rep(letters[1:5], each=10),
    value = cumsum(rnorm(50))
)

And i'm not sure exactly what you tried, but scale_color_manual should have worked. And if you want to change the line type you need to set that in the aes()

library(ggplot2)
library(scales)

ggplot(rmm, aes(x=timestamp, y=value, 
    color=serviceInstanceName, linetype=serviceInstanceName)) +
stat_smooth(size=1.5, method = "loess", level = 0.95, 
    fullrange = TRUE, se = FALSE) + 
scale_x_datetime(breaks = date_breaks("1 day"), 
    labels = date_format("%a/%m")) + 
theme(axis.text.x = element_text(angle = 90, hjust = 1)) + xlab("Day")  + 
ylab("Utility") + ggtitle("Utility Trend") + 
scale_color_manual(values=c(a="orange",b="yellow",
    c="red", d="sienna",e="cornsilk"))

enter image description here

like image 167
MrFlick Avatar answered Oct 02 '22 13:10

MrFlick