steve
steve

Reputation: 531

ggplot2 - change line color depending on variable name

I would like to plot the values of several tables. Each of these tables have a different/unknown number of variables/columns.

I am using the following code in order to plot the data:

library(ggplot2)
library(reshape2)
#data <- read.table("jony.csv", header = TRUE, sep = ";", fill = TRUE)
data <- read.table(text="MONTH;GFDL.ESM2M_HBV_IWW_WFDisi;GFDL.ESM2M_SWIM;GFDL.ESM2M_WaterGAP3;GFDL.ESM2M_HYPE;GFDL.ESM2M_VIC;month_mean;q70
1;853.455161290323;550.116774193548;746.965913978495;469.31688172043;546.64752688172;633.300451612903;452.931661075269
2;1037.55011792453;632.34445754717;805.189285714286;567.411202830189;763.929245283019;761.284861859839;452.931661075269
3;782.714301075269;447.378494623656;561.674193548387;422.475483870968;591.257634408602;561.100021505376;452.931661075269
", header = TRUE, sep = ";", fill = TRUE)
jony <- melt(data, id.vars="MONTH")
p <- ggplot(jony, aes(MONTH,value, col=variable))
p + geom_line(size = 0.1) +
  geom_hline(aes(yintercept = 0), linetype="dotted") +
  ylab("Runoff [m3/s]") +
  xlab("Month") +
  theme_bw() +
  theme(legend.key = element_blank())+
  scale_color_discrete(name='Models GCM_HM') +
  ggtitle("Jony")

So with this code, ggplot2 assign automatically a color for each of my variables. My problem is that I would like to assign manually a color just for the last two variables "month_mean" and "q70". I have tried different ways, but it seems that then I need to assign manually a color for each of my variables (which is not making sens in my case because I have way too many data to threat and the number of variables is not constant). Does anyone knows a workaround in order to assign manually a color for those two variables?

Upvotes: 1

Views: 1378

Answers (1)

lukeA
lukeA

Reputation: 54237

Maybe use some sort of a helper function, e.g.

p <- ggplot(jony, aes(MONTH,value, col=variable)) + 
  geom_line(size = 0.1) +
  geom_hline(aes(yintercept = 0), linetype="dotted") +
  ylab("Runoff [m3/s]") +
  xlab("Month") +
  theme_bw() +
  theme(legend.key = element_blank())+
  scale_color_discrete(name='Models GCM_HM') +
  ggtitle("Jony") 

f <-  function(x,cols,pal=rainbow) {
  stopifnot(names(cols) %in% x)
  pal <- pal(length(x)-length(cols))
  names(pal) <- setdiff(x, names(cols))
  pal <- c(pal, cols)
  return(pal)
}
p + scale_color_manual(
  values = f(levels(jony$variable), c("month_mean"="black", "q70"="cyan"), grey.colors )
)

Probably room for improvement, but...

Upvotes: 2

Related Questions