如何在ggplot中为每个方面添加图例?

时间:2018-11-12 08:29:00

标签: r ggplot2

我有以下data.frame。我想绘制一个具有三个图例表,大小通用的图例以及两个单独的图例的ggplot,其中gg =“ A”和var =“ B”从'值'列中获取值,这两个图例应放置在旁边每个相关图。到目前为止,我已经尝试过为“ var”列创建单个图例。

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))

谢谢。

编辑: 我已附上@Tung建议的预期输出 enter image description here

1 个答案:

答案 0 :(得分:2)

那这样的事情呢?

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