我正在尝试将一些图表相互匹配。有些是在 Sigmaplot 中制作的,我无权访问数据。所以这意味着我的新图表必须看起来尽可能相似,我正在使用它ggplot来实现这一点。我添加了 100 万个小细节,使它们更相似,但我仍然无法理解其中一个细节。
线端应该是四舍五入的,我已经通过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")
Run Code Online (Sandbox Code Playgroud)
在 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)
}
Run Code Online (Sandbox Code Playgroud)
我们可以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, ...))}
Run Code Online (Sandbox Code Playgroud)
结果:
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
)
Run Code Online (Sandbox Code Playgroud)