首页 文章

带有辅助变量的颜色的ggplot图例

提问于
浏览
3

我想用黑色的二次曲线和不同颜色的不同颜色的水平线创建一个图表,标注水平线条颜色的图例(指南) . 我无法弄明白 - 我尝试了几种似乎对我有意义的变化,但我似乎无法强迫传奇出现 .

这是我最近的尝试:

library(ggplot2)
theme_set(theme_bw()) ## cosmetic
hdat <- data.frame(harvest_rate=c(5,15,25,30))
r <- 1; K <- 100
ggplot(hdat)+
    geom_hline(data=hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+
    expand_limits(x=c(0,110))

enter image description here

线条出来没问题,但传说/指南不存在 .

如果我这样做:

ggplot(hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
    geom_hline()+
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+
    expand_limits(x=c(0,110))

然后令我惊讶的是水平线根本没有画出来!

我也试过(我开始这样做)设置一个带有 xy 变量的数据框,

d <- data.frame(x=0:110)
 d <- transform(d,y=r*x*(1-x/K))
 ggplot(d,aes(x,y))+geom_line()+
      geom_hline(data=hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
      scale_colour_brewer(palette="Set1")

该指南也没有显示出来 .

如果我在初始 ggplot 调用中设置 colour=NA ,则会出现图例,但曲线消失 . 如果我按如下方式设置 colour=factor(1)

ggplot(d,aes(x,y,colour=factor(1)))+geom_line()+
      geom_hline(data=hdat,aes(yintercept=harvest_rate,
               colour=factor(harvest_rate)))+
      scale_colour_brewer(palette="Set1")

我得到一条曲线和一个传奇,但曲线是假的颜色 . 如果我通过设置 geom_line(colour="black") 覆盖,则图例再次消失...

我将非常感谢(1)一个有效的黑客和(2)对我所缺失的逻辑的解释!

1 回答

  • 3

    完整答案:

    library(ggplot2)
    theme_set(theme_bw()) ## cosmetic
    hdat <- data.frame(harvest_rate=c(5,15,25,30))
    r <- 1; K <- 100
    
    ggplot(hdat)+
      geom_hline(aes(yintercept=harvest_rate, colour=factor(harvest_rate)), show_guide=TRUE)+
      stat_function(fun=function(x) r*x*(1-x/K),colour="black")+
      expand_limits(x=c(0,110)) +
      labs(colour = "Harvest rate") # making a pretty legend title
    

    结果:

    enter image description here

相关问题