Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

color and change line type in a ggplot by group

Tags:

r

ggplot2

I have a dataframe so far as follows:

  N Method1-Simulation Method1-Analytical Method2-Simulation Method3-Analytical
1 2              0.094          0.1831891              0.158          0.2789826
2 3              0.236          0.2856285              0.434          0.4670031
3 4              0.349          0.3740548              0.568          0.6097311
4 5              0.450          0.4525999              0.682          0.7174169
5 6              0.506          0.5228121              0.781          0.7976934
6 7              0.585          0.5854665              0.851          0.8566850

It will grow to accommodate more methods. I want to make a ggplot where each method has it's own color and the analytical method is a solid line while the simulation method is a broken line.

I have everything but the broken line as follows:

longPowerCurve <- melt(powerCurve, id = "N")
colnames(longPowerCurve)[2] <- "Method"

ggplot(data=longPowerCurve,aes(x=N, y=value, colour=Method)) + geom_line() +ylab("Power") +ggtitle("Power levels for various N and distributions")+
  theme(legend.text = element_text(size = 12))

Is there a way I can automate this so that if I have 5, 6,7,8, etc methods, it all still works?

like image 665
user1357015 Avatar asked Feb 16 '15 17:02

user1357015


1 Answers

You probably want to split the method.type column. In that way, you can use the two factors separately for your plot. To have the dotted line, you would use the linetype parameter.

groups <- data.frame(do.call('rbind', strsplit(as.character(longPowerCurve$Method),'.',fixed=TRUE)))
colnames(groups) <- c("Method", "Type")
longPowerCurve$Method <- groups$Method
longPowerCurve$Type <- groups$Type

ggplot(data=longPowerCurve,aes(x=N, y=value, colour=Method, linetype=Type)) + 
  geom_line() +
  ylab("Power") +
  ggtitle("Power levels for various N and distributions")+
  theme(legend.text = element_text(size = 12))

enter image description here

like image 159
cdeterman Avatar answered Sep 29 '22 14:09

cdeterman