Create a border around `geom_line` in ggplot2

Advertisements

In geom_point adding a black border around the points (geom_point) is easily possible using pch = 21 and a fill and colour command.

Example:

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point(aes(fill=Species), pch=21, color="black")

However this does not work for Lineplots (geom_line):

df <- data.frame(Group=rep(c("G1", "G2"), each=3),
                  X_Value= seq(1,3,1),
                  Y_Value=c(6.9, 15, 1.5, 2.2, 12, 29.7))

ggplot(data=df, aes(x=X_Value, y=Y_Value, fill=Group)) +
  geom_line(size=2, aes(colour= Group))+
  geom_point(pch=21, colour= "black", size=4, aes(colour=Group))+
  scale_fill_brewer(palette = "Set1")

#This does not work:

ggplot(data=df, aes(x=X_Value, y=Y_Value, fill=Group)) +
  geom_line(size=2, aes(colour= Group))+
  geom_point(pch=21, colour= "black", size=4, aes(colour=Group))+
  scale_fill_brewer(palette = "Set1")

Is there a way to have a black border around the line plot as well?

>Solution :

An easy solution is to just plot a slightly wider black line behind the line you already have.

library(ggplot2)

df <- data.frame(Group=rep(c("G1", "G2"), each=3),
                 X_Value= seq(1,3,1),
                 Y_Value=c(6.9, 15, 1.5, 2.2, 12, 29.7))

ggplot(data=df, aes(x=X_Value, y=Y_Value, fill=Group)) +
  geom_line(size=2 * 1.5, aes(group= Group), colour = "black")+
  geom_line(size=2, aes(colour= Group))+
  geom_point(pch=21, colour= "black", size=4, aes(colour=Group))+
  scale_fill_brewer(palette = "Set1")

Created on 2022-08-29 by the reprex package (v2.0.0)

Another solution you might like is the {ggborderline} package, though I’ve not used it myself.

Leave a Reply Cancel reply