1
votes

I've searched and tried a bunch of suggestions to be able to display a custom legend instead of the default one in a grouped scatter ggplot. I've tried this and this and following this among others.

For instance, let's say I have a df like this one:

df = data.frame(id = c("A", "A", "B", "C", "C", "C"), 
                value = c(1,2,1,2,3,4), 
                ref = c(1.5, 1.5, 1, 2,2,2), 
                min = c(0.5, 0.5, 1,2,2,2))

and I want to display the values of each id as round dots, but also put the reference values and minimum values for each id as a differently shaped dot, as follows:

p = ggplot(data = df) +
  geom_point(aes(x = id, y = value, color = factor(id)), shape = 19, size = 6) +
  geom_point(aes(x = id, y = ref, color = factor(id)), shape = 0, size = 8) +
  geom_point(aes(x = id, y = min, color = factor(id)), shape = 2, size = 8) +
  xlab("") +
  ylab("Value")
#print(p) 

Now all is fine, but my legend doesn't add anything to the interpretation of the plot, as the X axis and colors are enough to understand it. I know I can remove the legend via theme(legend.position = "none"). Instead, I would like to have a legend of what the actual shapes of each dot represent (e.g., filled round dot = value, triangle = min, square = ref).

Among trying to manually set the scale values via scale_fill_manual and something along those lines

override.shape = shapes$shape
override.linetype = shapes$pch
guides(colour = guide_legend(override.aes = list(shape = override.shape, linetype = override.linetype)))...
....

I've also tried making a secondary plot, but not display it, using something suggested in one of the links pasted above:

shapes  = data.frame(shape = c("value", "reference", "minimum"), pch = c(19,0,2), col = c("gray", "gray", "gray"))
p2 = ggplot(shapes, aes(shape, pch)) + geom_point()  
#print(p2)

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}
legend <- g_legend(p2)
library(gridExtra)
pp <- arrangeGrob(p1 ,legend,
                  widths=c(5/4, 1/4),
                  ncol = 2)

but then I get the error:

> legend <- g_legend(p2)
Error in tmp$grobs[[leg]] : 
  attempt to select less than one element in get1index

for which I did not find a working solution.. so yeah.. any suggestion on how I could only show a legend related to the different dot shapes would be welcome. Thank you

2
Just add shape and size to the aesthetics you're mapping on, alongside color. Or am I missing something more complicated? - camille
Thanks for the comment. adding shape geom_point(aes(x = id, y = value, color = factor(id), shape = 19), size = 6) (size is not important in this context) results in this error: Error: A continuous variable can not be mapped to shape. If it makes a difference, shape is not part of the dataframe, but maybe I should add it there!? - Marius
You'll want to map it to some variable, like whatever it is that differentiates the first geom_point call from the second. But that points to a bigger problem, which is that ggplot is generally intended to be used on long-shaped data where you're not making repeat calls to the same geom just to change some visual element. Maybe take a look at a couple tutorials and see how you could reshape the data - camille
well, that's why i was trying to create a different plot and not display it, just to generate the legend from a simpler df. because those three sets of points (value, ref, minimum) come from three different columns within the df. so yeah. thought i can just disable the "default" legend and "stitch" a new one :/ - Marius
The fact that they're in different columns is why you want to reshape the data, so there's a column of values and a column of what they mean (value, ref, or min). Here's one example datascience.stackexchange.com/q/66590/50633 - camille

2 Answers

2
votes

You can manually build a shape legend using scale_shape_manual:

library(ggplot2)

ggplot(data = df) +
  geom_point(aes(x = id, y = value, color = factor(id), shape = 'value'), size = 6) +
  geom_point(aes(x = id, y = ref, color = factor(id), shape = 'ref'), size = 8) +
  geom_point(aes(x = id, y = min, color = factor(id), shape = 'min'), size = 8) +
  scale_shape_manual(values = c('value' = 19, 'ref' = 0, 'min' = 2)) +
  xlab("") +
  ylab("Value")

Created on 2020-04-15 by the reprex package (v0.3.0)

But a better way to do this would be to reshape the df to a long format, and map each aes to a variable:

library(dplyr)
library(tidyr)

df %>% 
  pivot_longer(-id) %>% 
  ggplot() +
  geom_point(aes(x = id, y = value, color = factor(id), shape = name, size = name)) +
  scale_shape_manual(values = c('value' = 19, 'ref' = 0, 'min' = 2)) +
  scale_size_manual(values = c('value' = 6, 'ref' = 8, 'min' = 8)) + 
  xlab("") +
  ylab("Value")

Created on 2020-04-15 by the reprex package (v0.3.0)

To remove the legend for the color use guide_none():

library(tidyr)
library(ggplot2)
df %>% 
  pivot_longer(-id) %>% 
  ggplot() +
  geom_point(aes(x = id, y = value, color = factor(id), shape = name, size = name)) +
  scale_shape_manual(values = c('value' = 19, 'ref' = 0, 'min' = 2)) +
  scale_size_manual(values = c('value' = 6, 'ref' = 8, 'min' = 8)) + 
  guides(color = guide_none()) +
  xlab("") +
  ylab("Value")

Created on 2020-04-16 by the reprex package (v0.3.0)

Data:

df = data.frame(id = c("A", "A", "B", "C", "C", "C"), 
                value = c(1,2,1,2,3,4), 
                ref = c(1.5, 1.5, 1, 2,2,2), 
                min = c(0.5, 0.5, 1,2,2,2))
2
votes

You can tidy your data first using tidyr, and then map the aes shape to the new variable

library(tidyr)
df2 <- pivot_longer(df, -id)

ggplot(data = df2) +
  geom_point(aes(x = id, y = value, shape = name), size = 6) +
  xlab("") +
  ylab("Value")

enter image description here