Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control point border thickness in ggplot

When using ggplot, I can set shape to 21-25 to get shapes that have independent setting for the internal (fill) and border (col) colors, like so:

df <- data.frame(id=runif(12), x=1:12, y=runif(12)) ggplot(df, aes(x=x, y=y)) +    geom_point(aes(fill=id, size=id), colour="black", shape=21) 

enter image description here

However, I can't figure out how to control the thickness of the shape borders, either setting them absolutely or as an aesthetic mapping. I note that if I set an lwd value, it overrides the size aesthetic:

ggplot(df, aes(x=x, y=y)) +    geom_point(aes(fill=id, size=id), colour="black", shape=21, lwd=2) 

enter image description here

How do I control the border thickness?

like image 362
Noam Ross Avatar asked Oct 21 '13 23:10

Noam Ross


People also ask

How do I change border thickness in R?

Now to change the thickness of border, we simply use a parameter inside geom_point() function called stroke, which specify the thickness of the border of points in Scatterplot.

How do I change the thickness of a line in ggplot2?

To change line width, just add argument size=2 to geom_line().

How do I change the shape of a point in ggplot2?

Change point shapes, colors and sizes manually : The functions below can be used : scale_shape_manual() : to change point shapes. scale_color_manual() : to change point colors. scale_size_manual() : to change the size of points.

What is geom_point?

geom_point.Rd. The point geom is used to create scatterplots. The scatterplot is most useful for displaying the relationship between two continuous variables.


2 Answers

It feels a bit hacky but you can add a "background" set of dots with the size set to the aesthetic mapping plus some small constant to enlarge the border of the dots. Play with the constant to get the desired border width.

You'll also have to disable the size legend to stop it displaying the legend on the graph...

ggplot(df, aes(x=x, y=y)) +    geom_point(aes(size=id+0.5), colour="black" , show_guide = FALSE )+   scale_size( guide = "none" )+   geom_point(aes(fill=id, size=id), colour="black", shape=21) 

enter image description here

like image 38
Simon O'Hanlon Avatar answered Sep 22 '22 05:09

Simon O'Hanlon


Starting in version 2.0.0 of ggplot2, there is an argument to control point border thickness. From the NEWS.md file:

geom_point() gains a stroke aesthetic which controls the border width of shapes 21-25 (#1133, @SeySayux). size and stroke are additive so a point with size = 5 and stroke = 5 will have a diameter of 10mm. (#1142)

Thus, the correct solution to this is now:

df <- data.frame(id=runif(12), x=1:12, y=runif(12)) ggplot(df, aes(x=x, y=y)) +    geom_point(aes(fill=id, size=id), colour="black", shape=21, stroke = 2) 

Output

like image 73
Noam Ross Avatar answered Sep 20 '22 05:09

Noam Ross