在ggplot中制作舍入的行尾-在图例和图例中

时间:2019-02-21 23:28:41

标签: r ggplot2

我正在尝试使某些图形相互匹配。有些是使用Sigmaplot制作的,我无权访问数据。因此,这意味着我的新图形必须看起来尽可能相似,而我正在使用ggplot来实现。我添加了一百万个细微的细节,以使它们更加相似,但是一个细节仍然使我难以理解。

应该将行的末端舍入,这是我通过在lineend = "round"中设置geom_line()来完成的。但是,图例中的线末端仍然有一个对接末端。我是坚持一致的人,每个细节都是如此,这意味着我真的不能接受...

这里是一个例子。

var1 <- seq(1,100,10)
var2 <- c(1:10)
trt <- c("t1", "t1", "t1", "t1", "t1", "t2", "t2", "t2", "t2", "t2")
my.df <- data.frame(var1, var2, trt)


ggplot(data = my.df, aes(x = var1, y = var2, col = trt))+
  geom_line(size = 3, lineend = "round")

1 个答案:

答案 0 :(得分:3)

在ggplot2程序包中,geom_line的图例键被硬编码为lineend = "butt"

> GeomLine$draw_key
<ggproto method>
  <Wrapper function>
    function (...) 
f(...)

  <Inner function (f)>
    function (data, params, size) 
{
    data$linetype[is.na(data$linetype)] <- 0
    segmentsGrob(0.1, 0.5, 0.9, 0.5, gp = gpar(col = alpha(data$colour, 
        data$alpha), lwd = data$size * .pt, lty = data$linetype, 
        lineend = "butt"), arrow = params$arrow)
}

我们可以使用图例键geom_line2()来定义自己的略有不同的版本lineend = "round"

library(grid)

GeomLine2 <- ggproto(
  "GeomLine2", GeomLine,
  draw_key =  function (data, params, size) {
    data$linetype[is.na(data$linetype)] <- 0
    segmentsGrob(0.3, 0.5, 0.7, 0.5, # I modified the x0 / x1 values here too, to shift
                                     # the start / end points closer to the centre in order
                                     # to leave more space for the rounded ends
                 gp = gpar(col = alpha(data$colour, data$alpha), 
                           lwd = data$size * .pt, 
                           lty = data$linetype, 
                           lineend = "round"),
                 arrow = params$arrow)
  })

geom_line2 <- function (mapping = NULL, data = NULL, stat = "identity", position = "identity", 
                        na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) {
  layer(data = data, mapping = mapping, stat = stat, 
        geom = GeomLine2, # this is the only change from geom_line to geom_line2
        position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
        params = list(na.rm = na.rm, ...))}

结果:

cowplot::plot_grid(

  ggplot(data = my.df, aes(x = var1, y = var2, col = trt))+
    geom_line(size = 3, lineend = "round") +
    ggtitle("original geom_line"),

  ggplot(data = my.df, aes(x = var1, y = var2, col = trt))+
    geom_line2(size = 3, lineend = "round") +
    ggtitle("modified geom_line2"),

  ncol = 1
)

plot