Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a border around `geom_line` in ggplot2

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading