ggplot2 - 根据变量名称更改线条颜色

时间:2016-09-05 16:25:04

标签: r variables ggplot2 colors

我想绘制几个表的值。这些表中的每一个都有不同/未知数量的变量/列。

我使用以下代码绘制数据:

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")

因此,使用此代码,ggplot2会自动为每个变量分配颜色。我的问题是我想手动为最后两个变量分配一种颜色&#34; month_mean&#34;和&#34; q70&#34;。我尝试了不同的方法,但似乎那时我需要为我的每个变量手动分配一个颜色(在我的情况下这不是很敏感,因为我有太多的数据威胁和变量的数量不是恒定的) 。有没有人知道一种解决方法,为这两个变量手动分配颜色?

1 个答案:

答案 0 :(得分:2)

也许使用某种帮助函数,例如

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 )
)

可能还有改进的余地,但是......