Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add legend in ggplot for each facet?

Tags:

r

ggplot2

I have the following data.frame. I want to draw a ggplot having three legend tables, the common legend for size, and two separate legends for var = "A" and var = "B" taking the values from 'value' column, these two legends should be placed next to each related graph. So far I have tried this which is creating a single legend for 'var' column.

df <- data.frame(var = c("A","A","B","B"),
                 value = c("u","v","x","y"),
                 point = 1:4,
                 size = 1:4)

ggplot() +geom_point(data = df, 
                     aes(x = point,y = NA,
                         color = value,size = size)) +  
    facet_grid(rows = vars(var))

Thanks.

Edit: I have attached the expected output as suggested by @Tung enter image description here

like image 570
Raja Saha Avatar asked Nov 12 '18 08:11

Raja Saha


1 Answers

What about something like this:

library(gridExtra)
library(ggplot2)
# split data for each "facet"
df <- split(df,f = df$var)

# plot for the first "facet"
p1 <- ggplot(df$A,aes(x = point,y = NA,colour = value, size = size)) + 
  geom_point() + 
  facet_wrap(~var, ncol=1) +
  # here you set the axis
  scale_x_continuous(limits = c(0.5, 4.5))

# do it for each "facet"
p2 <- p1 %+% df$B

# here the plot
grid.arrange(p1,p2)

enter image description here

like image 111
s__ Avatar answered Nov 05 '22 10:11

s__