使用 ggplot2 平滑可变线宽边框

Smoothing variable line size borders using ggplot2

我正在制作一个线图,其中线的粗细被映射到第三个连续变量。但是,当将变量映射到 geom_line 的大小参数时,生成的图会生成一个由看起来不连贯的线条组成的“矮胖”图。有没有一种方法可以平滑地混合这些线,使线段之间没有明显的间隙?

我在下面制作了一个可重现的例子。

data(mtcars)
require(ggplot2)
mtcars$am<-factor(mtcars$am)
ggplot(data=mtcars,aes(x=mpg,y=hp))+geom_line(aes(color=am,size=disp))

生成以下图:

例如,我想将 am=0 的第一条线段的边界与第二条线段的边界混合。

感谢您的帮助。

您可以通过切换到 geom_path 来做得更好一点,它遵循线条结束和连接形状的指令:

ggplot(data=plyr::arrange(mtcars,mpg),
       aes(x=mpg,y=hp))+
geom_path(aes(color=am,size=disp),lineend="round",linejoin="mitre")

来自?geom_path

lineend: Line end style (round, butt, square)

linejoin: Line join style (round, mitre, bevel)

(虽然还是有点难看...)

有点疯狂:

library("ggplot2")
library("grid")
theme_set(theme_bw()+theme(axis.line=element_blank(),axis.text.x=element_blank(),
          axis.text.y=element_blank(),axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),legend.position="none",
          panel.background=element_blank(),
          panel.border=element_blank(),panel.grid.major=element_blank(),
          panel.grid.minor=element_blank(),plot.background=element_blank(),
          panel.margin=unit(0,"lines")))


library(gridExtra)
ggList <- list()
for (end in c("round","butt","square")) {
    for (join in c("round","mitre","bevel")) {
        ggList <- c(ggList,
                    list(ggplot(data=plyr::arrange(mtcars,mpg),
                                aes(x=mpg,y=hp))+
                             geom_path(aes(color=factor(am),size=disp),
                                       lineend=end,linejoin=join)+
                                 scale_size(guide="none")+
                                     scale_colour_discrete(guide="none")))
    }
}

png("linejoin.png",500,500)
do.call(grid.arrange,ggList)
dev.off()

看起来 join 参数没有做任何事情,可能是因为 ggplot 将路径的每个部分绘制为单独的段 ...