Reputation: 3650
I have two data frames likes this:
library(ggplot2)
set.seed(1)
x1 = rnorm(100)
y1 = rnorm(100)
x2 = rnorm(100)
y2 = rnorm(100)
df1 = data.frame(x=x1, y=y1, col1 = rep(1:4, each = 25))
df2 = data.frame(x=x2, y=y2, col2 = rep(5:8, each = 25))
I plot this data:
ggplot() +
geom_point(aes(x = x1, y = y1, colour = as.factor(col1)), data = df1, size = 1, shape = 19) +
geom_point(aes(x = x2, y = y2, colour = as.factor(col2)), data = df2, size = 2, shape = "\u2605")
The results is this:
How can I get two separate legends for each data frame? The legends should also correctly reflect the shapes used and let me specify legend titles for each legend.
I know that this solution exists but it's rather old and requires symbols that can take fills, I want to use custom unicode symbols.
Upvotes: 2
Views: 106
Reputation: 125897
This can be achieved via the ggnewscale
package which allows to have additional scales and legends for the same aestethic. Try this:
library(ggplot2)
set.seed(1)
x1 = rnorm(100)
y1 = rnorm(100)
x2 = rnorm(100)
y2 = rnorm(100)
df1 = data.frame(x=x1, y=y1, col1 = rep(1:4, each = 25))
df2 = data.frame(x=x2, y=y2, col2 = rep(5:8, each = 25))
ggplot() +
geom_point(aes(x = x1, y = y1, colour = as.factor(col1)), data = df1, size = 1, shape = 19) +
ggnewscale::new_scale_color() +
geom_point(aes(x = x2, y = y2, colour = as.factor(col2)), data = df2, size = 2, shape = "\u2605")
Upvotes: 2