如何在ggplot2中为geom_col的边框着色以避免重叠?

iro*_*est 5 r ggplot2

我想为 ggplot2 中的条形图边框着色。

以下脚本是一个示例。

如您所见,橙色边框与蓝色边框重叠。有什么方法可以避免这种行为并为图表内的边框着色吗?


library(tidyverse)
dat <- tibble(
  dx = c("D+","D+","D-","D-"),
  test    = c("T+","T-","T+","T-"),
  num     = c(40,80,100,800)
)

ggplot(dat) +
  geom_col(aes(x = dx, y = num, fill = dx, color = test),
           size = 3) +
  scale_color_manual(values = c("orange","blue"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

All*_*ron 3

问题是条形图是用 构建的grid::rectGrob,当你画出更大的轮廓时rectGrob,它就会变大。由于线条是固定点大小,但条形本身不是(正如您更改窗口大小时会看到的那样),因此没有简单的方法可以缩小 srectGrob来补偿这一点以允许内部轮廓。因此,这实际上是一个比最初出现时更难解决的问题。当然,这并非不可能,但您的三个选择是:

  1. 选择不同的绘图方式(如position_dodge
  2. 通过临时 hack 达到您想要的效果
  3. 写一个全新的geom来达到效果(或者找一个已经做到这一点的包)

如果这只是一次性的,并且您热衷于追求特定的情节外观,我肯定会选择选项 2。以下是如何实现它的示例:

ggplot(dat) +
  geom_col(aes(x = dx, y = num, fill = dx, color = test),
           size = 3) +
  scale_color_manual(values = c("orange","blue")) +
  geom_segment(aes(x = 0.53, y = 100, xend = 1.465, yend = 100), 
               size = 3, colour = "blue") +
  geom_segment(aes(x = 0.53, y = 120, xend = 1.465, yend = 120), 
               size = 3, colour = "orange") +
  geom_segment(aes(x = 1.53, y = 40, xend = 2.465, yend = 40), 
               size = 3, colour = "blue") +
  geom_segment(aes(x = 1.53, y = 60, xend = 2.465, yend = 60), 
               size = 3, colour = "orange") 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述