R ggplot2更改*特定*线型图例的背景颜色

时间:2020-06-16 12:03:49

标签: r ggplot2

这里是一个类似的问题,但是该解决方案不适用于scale_linetype_manualSimilar but not the same SO question。 当我使用legend.key参数时,它只会在我的比例尺行之后插入 。 (请参见下面的图片)

现在我的图上所有内容都可以处理,除了我的图具有白色背景,并且scale_linetype_manual正在插入灰色背景。

enter image description here

当我使用legend.key参数时,这就是我得到的(我将其设置为黑色,因此它是可见的,即legend.key=element_rect(fill="#000000")):

enter image description here

如您所见,它在灰色的矩形后面 添加了一个黑色的矩形。

如何更改灰色矩形的颜色?

这是ggplot2代码:

p = ggplot()+
    theme(axis.line.y.right = element_line(color = "#FF00FF"), 
          axis.ticks.y.right = element_line(color = "#FF00FF"),
          axis.text.y.right = element_text(color = "#FF00FF"), 
          axis.title.y.right = element_text(color = "#FF00FF"),
          panel.background = element_rect(fill="white",color="black"),
          legend.key=element_rect(fill="#000000"))+

    geom_rect(data=df2, mapping=aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,fill=color),show.legend = T)+
    scale_fill_manual(name="Codon type",values=c('#FFEBCC','#E6FFF7','#F2F2F2'),
                      labels=c("CR","NCR","None"),
                      limits=c("CR","NCR","None"))+

    #-----This should be the relevant part-----
    geom_path(data=df,aes(x=resseqnum,y=y.sec,color='b',linetype='b'))+
    geom_path(data=df,aes_string(x='resseqnum',y='cen',color='a',linetype='a'),size=.5)+
    geom_path(aes(x=c(x.min,x.max),y=c(a,a),color='c',linetype='c'))+
    scale_linetype_manual(name="Lines",values=c("a"='solid',"b"='solid',"c"='dotted'),
                          labels=c('Centrality','Minmax','Zero reference'))+
    scale_color_manual(name="Lines",values=c('#00FF00','#FF00FF','#FF00FF'),
                       labels=c('Centrality','Minmax','Zero reference'))+
    #-----Possible end of relevant part-----    

    scale_y_continuous("Centrality",sec.axis=sec_axis(~ (. - a)/b,name="Minmax"))+
    scale_x_continuous("Sequence location")+
    coord_cartesian(xlim=c(0,10))+

    ggtitle("Title")

为了重现性:

df.txt

resseqnum,cen,y.sec
1,4,3
2,5,6
3,6,3
4,NA,NA
5,NA,NA
6,6,4
7,3,2
8,1,3
9,5,3
10,10,5

df2.txt

xmin,xmax,ymin,ymax,color
1,2,1,10,CR
5,7,1,10,NCR
9,10,1,10,None

其他:

b=2.25
a=5

1 个答案:

答案 0 :(得分:1)

您需要添加

guides(linetype = guide_legend(override.aes = list(fill = "#000000")))

在您的情节中,您会得到类似这样的信息:

enter image description here