0

For scatterplots with many points, one common technique is to reduce the size of the points and to make them transparent.

library(ggplot2)
ggplot(diamonds, aes(x, y, colour = cut)) +
  geom_point(alpha = 0.25, size = 0.5) +
  ylim(0, 12)

A scatterplot of the diamonds dataset with points reduced in size and opacity.  The points in the legend are hard to see.

Unfortunately, the points in the legend are now too small and faint to see properly.

I would like a way to change the points in the legend independently of the plots in the main plot panel. It ought to be one of the setting contained in:

thm <- theme_get()
thm[grepl("legend", names(thm))]

I'm struggling to find the appropriate setting though. How do I change the point size?

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360

2 Answers2

2

You can use the function guide_legend() in package scales to achieve your effect.

This function allows you to override the aes values of the guides (legends) in your plot. In your case you want to override both alpha and size values of the colour scale.

Try this:

library(ggplot2)
library(scales)
ggplot(diamonds, aes(x, y, colour = cut)) +
  geom_point(alpha = 0.25, size = 1) +
  ylim(0, 12) +
  guides(colour=guide_legend(override.aes=list(alpha=1, size=3)))

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496
1

If you need to change formatting only in the legend you should use override.aes= and size= in guide_legend (see below). This will override size used in plot and will use new size value just for legend.

To get points in legend and lines in plot workaround would be add geom_point(size=0) to ensure that points are invisible and then in guides() set linetype=0 to remove lines and size=3 to get larger points.

ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw()+ geom_point(size=0)+ guides(colour = guide_legend(override.aes = list(size=3,linetype=0))) enter image description here

Hack-R
  • 22,422
  • 14
  • 75
  • 131