首页 > 解决方案 > R ggplot 2图例边框问题

问题描述

我知道这是次要的,但它是为了出版,会让我发疯。P0688 盒子的底部比其余的要薄 1-2 个像素。我不想让边框变粗,因为它与条形图的其余部分不匹配。

  plot<- ggplot(tukey_letters, aes(x = variable, y = value.x, 
        fill = L1)) + 
      theme(panel.background=element_rect(fill="#ffffff", color 
      ="#000000"), panel.grid.major=element_blank(), 
    panel.grid.minor=element_blank()) +
      geom_bar(stat = "identity", position=position_dodge(),color="black")+ scale_fill_manual(values=c("#FFFFFF", "#999999"))+ guides(fill=guide_legend(title="Genotype", title.position = "left")) +
  geom_errorbar(aes(ymin=value.x-se, ymax=value.x+se), width=.1,size=.5,position=position_dodge(0.9), color="black")+
  theme(
    axis.title = element_text(size =12, face="bold"),
    axis.text = element_text(angle=30, vjust=0.5,hjust=0.6,size=8,face="bold", color="#000000"),
    axis.ticks = element_line(size = rel(1)),
    axis.ticks.length = unit(0.3, "cm"),
    legend.position = c(0.2, 0.9)
  )+
  labs(
    x="Treatment",
    y="ARI1"
  )+
  #facet_wrap(~L1)+ ## You can use face_wrap function only if you need it+
  geom_text(data =tukey_letters,
            aes(x=xpos, y=ymax+offset_asterisk,label=groups), 
           size = 4,position=position_dodge(0.9) , vjust=-0.5
 )

P0688 盒底

在较小的尺寸下甚至没有那么明显。 仍然困扰着我。

提前致谢。让我知道是否还有其他需要帮助解决此问题。

标签: rggplot2formattinglegend

解决方案


这是由于图例键的填充行为。这是一个已知问题,请参阅此 GitHub 线程https://github.com/tidyverse/ggplot2/issues/2844。这个网站上也有一个修复建议,让我在这里展示一下。

library(tidyverse)

ggplot(mtcars) +
  aes(fill=factor(cyl), x=cyl) +
  geom_bar(color = 'black') +
  guides(fill=guide_legend(title.position = "left")) +
  theme(legend.key = element_rect(color="white") +
        legend.position = c(0.2, 0.7))

放大后,图例现在看起来像这样: 在此处输入图像描述

现在让我们进行修复。

  draw_key_polygon3 <- function(data, params, size) {
  lwd <- min(data$size, min(size) / 4)

  grid::rectGrob(
    width = grid::unit(0.7, "npc"),
    height = grid::unit(0.7, "npc"),
    gp = grid::gpar(
      col = data$colour,
      fill = alpha(data$fill, data$alpha),
      lty = data$linetype,
      lwd = lwd * .pt,
      linejoin = "mitre"
    ))
}

GeomBar$draw_key = draw_key_polygon3

ggplot(mtcars) +
  aes(fill=factor(cyl), x=cyl) +
  geom_bar(color = 'black') +
  guides(fill=guide_legend(title.position = "left")) +
  theme(legend.key = element_rect(color="white", fill = 'white'),
        legend.position = c(0.2, 0.7))

在此处输入图像描述

但是这里到底发生了什么?让我们来看看!

ggplot(mtcars) +
  aes(fill=factor(cyl), x=cyl) +
  geom_bar(color = 'black') +
  guides(fill=guide_legend(title.position = "left")) +
  theme(legend.position = c(0.2, 0.7),
        legend.key = element_rect(color="black", fill = 'white')) 

传说有两个边界!一个用于图例字形,另一个用于键。您通过调用为键绘制边框theme,并使用您的颜色参数创建字形周围的边框geom_bar

在此处输入图像描述

reprex 包(v0.3.0)于 2020-04-04 创建


推荐阅读