Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smoothing variable line size borders using ggplot2

Tags:

r

ggplot2

I am producing a line plot where line thickness is mapped to a third continuous variable. However, when mapping the variable to the size parameter of geom_line, the resulting plot produces a "chunky" plot of disconnected looking lines. Is there a way I can smoothly blend these lines so that there are not glaring gaps between line segments?

I have produced a reproducible example below.

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

Produces the following plot: enter image description here

For instance, I would like to blend the border of the first line segment of am=0 with the second.

Thank you for your help.

like image 335
bjoseph Avatar asked Nov 29 '25 01:11

bjoseph


1 Answers

You can do a little bit better by switching to geom_path, which respects the directives for the ending and joining shapes of lines:

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

From ?geom_path:

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

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

(still seems a little ugly though ...)

Going a little bit crazy:

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()

enter image description here

It looks like the join parameter isn't doing anything, probably because ggplot draws each part of the path as a separate segment ...

like image 158
Ben Bolker Avatar answered Nov 30 '25 14:11

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!