gpt4 book ai didi

r - 在 ggplot 中制作圆形线端 - 在情节和图例中

转载 作者:行者123 更新时间:2023-12-04 09:36:27 28 4
gpt4 key购买 nike

我正在尝试将一些图表相互匹配。有些是在 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")

最佳答案

在 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

关于r - 在 ggplot 中制作圆形线端 - 在情节和图例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54817837/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com