【问题标题】:R ggplot2 change background color of *specifically* linetype legendR ggplot2更改*特别*线型图例的背景颜色
【发布时间】:2020-06-16 12:03:49
【问题描述】:

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

除了我的图表有白色背景和 scale_linetype_manual 正在插入灰色背景之外,我现在可以在我的图表上进行所有工作。

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

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

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

这里是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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你需要添加

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

    到你的情节,那么你会得到这样的东西:

    【讨论】:

    猜你喜欢
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多