Reputation: 2166
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:
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.
Upvotes: 3
Views: 1121
Reputation: 226557
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()
It looks like the join parameter isn't doing anything, probably because ggplot
draws each part of the path as a separate segment ...
Upvotes: 7