控制点边界厚度

在使用 ggplot 时,我可以将 shape设置为21-25,以获得具有独立的内部(fill)和边框(col)颜色设置的形状,如下所示:

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

然而,我不能弄清楚如何控制形状边界的厚度,无论是设置他们绝对或作为一个美学映射。我注意到,如果我设置一个 lwd值,它将覆盖 size美学:

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

enter image description here

如何控制边框厚度?

83226 次浏览

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

Another solution is to create the plot in R and then export it to a .svg file. The linewidth can then be changed using vector graphics editing software (e.g., Inkscape). This method is particularly useful when data points overlap.

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