开发者

Separate legend by facet for geom_segment and geom_point

开发者 https://www.devze.com 2022-12-07 22:07 出处:网络
I am interested in creating a figure akin to the below, which has a separate legend entry for each of four components: two geom_segment and two geom_point, which are grouped according to some facet (c

I am interested in creating a figure akin to the below, which has a separate legend entry for each of four components: two geom_segment and two geom_point, which are grouped according to some facet (corresponding to the color).

Separate legend by facet for geom_segment and geom_point

Here is a sample dataset, and some initial code.

x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y <- c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
z <- c(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)
s <- c(5, 5, 5, 5, 5, 5, 5, 5, 5, 5)
t <- c(10, 10, 10, 10, 10, 10, 10, 10, 10, 10)
n <- c("A", "A", "A",开发者_开发百科 "A", "A", "A", "A", "A", "A", "A",
       "B", "B", "B", "B", "B", "B", "B", "B", "B", "B")
df <- cbind(rbind(data.frame(x = x, y = y, s = s), data.frame(x = x, y = z, s = t)), n)

ggplot(data = df, mapping = aes(x = x, y = y, color = n)) +
  geom_point() +
  scale_color_manual(values = c("blue", "gray64")) +
  geom_segment(mapping = aes(x = 0, xend = 10, y = 10, yend = 10), color = "blue", inherit.aes = FALSE) +
  geom_segment(mapping = aes(x = 0, xend = 10, y = 20, yend = 20), color = "gray64", inherit.aes = FALSE)


Give this a shot:

library(ggplot2)

ggplot() + 
    geom_point(data = dplyr::filter(df, n == "A"), mapping = aes(x = x, y = y, shape = "Label A.1"), color = "gray") + 
    geom_point(data = dplyr::filter(df, n == "B"), mapping = aes(x = x, y = y, shape = "Label B.1"), color = "blue") + 
    geom_line(data = dplyr::filter(df, n == "A"), mapping = aes(x = x, y = s, color = "Label A.2")) + 
    geom_line(data = dplyr::filter(df, n == "B"), mapping = aes(x = x, y = s, color = "Label B.2")) + 
    scale_shape_manual(name = NULL, values = c(19, 19)) + 
    scale_color_manual(name = NULL, values = c("Label A.2" = "gray", "Label B.2" = "blue")) + 
    guides(shape = guide_legend(override.aes = list(color = c("Label A.1" = "gray", "Label B.1" = "blue"))))

ggplot2 doesn't seem to like separating legends (I suppose it does make the plot more complicated). In this solution, we add each layer separately, controlling the legend using shape (which we later set to 19, the default filled-in circle) and color aesthetics. In the last line, we make sure the colors of the shape layer are correct (try the code without the last line to see what it does!).

I also don't think "facet" is used correctly in your question. Generally, facets are like subplots.

0

精彩评论

暂无评论...
验证码 换一张
取 消