我正在尝试将一些图表相互匹配。有些是在Sigmaplot中制作的,我没有访问数据的权限。这意味着我的新图形必须看起来尽可能相似,我正在使用ggplot来实现这一点。我已经添加了一百万个微小的细节,以使它们更相似,但有一个细节仍然让我摸不着头脑。
线条末端应该是四舍五入的,我已经通过在geom_line()中设置lineend = "round"为绘图本身做到了这一点。但是,图例中的线条末端仍然有一个对接末端。我是一个坚持一致性的人,每一个细节都是如此,这意味着我真的不能接受……
下面是一个例子。
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")发布于 2019-02-22 09:39:04
在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)
}我们可以使用图例键lineend = "round"来定义我们自己的、稍有不同的geom_line2()版本:
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
)

https://stackoverflow.com/questions/54817837
复制相似问题