首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ggplot中创建圆角线端-在绘图和图例中都是如此

在ggplot中创建圆角线端-在绘图和图例中都是如此
EN

Stack Overflow用户
提问于 2019-02-22 07:28:41
回答 1查看 1.1K关注 0票数 4

我正在尝试将一些图表相互匹配。有些是在Sigmaplot中制作的,我没有访问数据的权限。这意味着我的新图形必须看起来尽可能相似,我正在使用ggplot来实现这一点。我已经添加了一百万个微小的细节,以使它们更相似,但有一个细节仍然让我摸不着头脑。

线条末端应该是四舍五入的,我已经通过在geom_line()中设置lineend = "round"为绘图本身做到了这一点。但是,图例中的线条末端仍然有一个对接末端。我是一个坚持一致性的人,每一个细节都是如此,这意味着我真的不能接受……

下面是一个例子。

代码语言:javascript
复制
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")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-22 09:39:04

在ggplot2包中,geom_line的图例密钥被硬编码为lineend = "butt"

代码语言:javascript
复制
> 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()版本:

代码语言:javascript
复制
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, ...))}

结果:

代码语言:javascript
复制
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
)

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54817837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档