【问题标题】:ggplot2 - change line color depending on variable nameggplot2 - 根据变量名称更改线条颜色
【发布时间】:2016-09-05 16:25:04
【问题描述】:

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

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

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 会自动为我的每个变量分配颜色。我的问题是我想为最后两个变量“month_mean”和“q70”手动分配颜色。我尝试了不同的方法,但似乎我需要为我的每个变量手动分配颜色(这在我的情况下没有意义,因为我有太多数据要威胁并且变量的数量不是恒定的) .有谁知道为这两个变量手动分配颜色的解决方法?

【问题讨论】:

    标签: r variables ggplot2 colors


    【解决方案1】:

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

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

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

    【讨论】:

    • 它有效,谢谢!有没有办法使用相同的函数来控制这两个变量的线型?
    • 不客气。您可以调整函数以使用 dotteddashed 等线条类型,而不是 redblue 等颜色,并将其传递给 scale_linetype_manual
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2021-12-26
    相关资源
    最近更新 更多