4

使用下面的数据,请注意图例没有正确描述 geom_hline:

df<-data.frame(
    points=c(.153,.144,.126,.035, .037, .039, .010,.015,.07),
    days=gl(3,1,9,labels=c("Sun","Mon","Tues")),
    lang=c("en","en","en","pt","pt","pt","ko","ko","ko")) 

ggplot(data=df[df$lang=="en",])+
    geom_point(aes(x=days,y=points),size=5,colour='cyan',show_guide=F)+
    geom_point(aes(x=days,y=points,colour=days),size=4,show_guide=F)+
    facet_wrap(~lang,ncol=1,scales="free")+
    xlab("")+
    ylab("")+
    scale_y_continuous(labels = percent_format())+
    theme(legend.position="right",
          legend.title = element_blank(),
          strip.text.x = element_text(size = 13, colour = 'black', angle = 0),
          axis.text.x=element_text(angle=0, hjust=.5, vjust=0),
          legend.position = 'none',
          panel.background = element_rect(fill = "#545454"),
          panel.grid.major = element_line(colour = "#757575"),
          panel.grid.minor = element_line(colour = "#757575"))+
    geom_hline(yintercept=.136,color='cyan',size=2, show_guide=T)

在此处输入图像描述

有没有办法创建一个描述 geom_hline 的自定义图例?[我希望图例的名称为“Legend”,只有一个值标记为“avg”]

搜索,我找到了一个例子:ggplot legend shows transparent and fill color。他们使用了我尝试过的 scale_fill_manual,但无法改进上面显示的图例。

4

1 回答 1

4

这有点尴尬,但这似乎有效:

hline <- data.frame(yint = 0.136,lt = 'Avg') 

ggplot(data=df[df$lang=="en",])+
    geom_point(aes(x=days,y=points),size=5,colour='cyan')+
    geom_point(aes(x=days,y=points,colour=days),size=4)+
    facet_wrap(~lang,ncol=1,scales="free")+
    xlab("")+
    ylab("")+
    scale_y_continuous(labels = percent_format())+
    theme(legend.position="right",
          legend.title = element_blank(),
          strip.text.x = element_text(size = 13, colour = 'black', angle = 0),
          axis.text.x=element_text(angle=0, hjust=.5, vjust=0),
          legend.position = 'none',
          panel.background = element_rect(fill = "#545454"),
          panel.grid.major = element_line(colour = "#757575"),
          panel.grid.minor = element_line(colour = "#757575"))+
    geom_hline(data = hline,aes(yintercept=yint,linetype = lt),color = "cyan",size=2,show_guide = TRUE) + 
    scale_colour_discrete(guide = "none") + 
    scale_linetype_manual(name = 'Legend',values = 1,guide = "legend")

在此处输入图像描述

啊,但是你已经包括legend.title = element_blank()在里面了,这就是为什么没有命名传说的原因。删除它以包含名称。

于 2013-06-13T17:21:40.863 回答