guir
guir

Reputation: 69

position of geom_vline() legend shifts

I have several plots like the one below. My problem is that the legend for geom_vline() (Type) shifts across plots, sometimes appearing above the "Mean" legend, sometimes below.

How can I specify the position of the geom_vline() legend (or the other legend), such that I do not have variation across plots in my paper?

set.seed(1234)
data <- data.frame(value = rnorm(n = 10000, mean = 50, sd = 20),
                   Type = sample(letters[1:2], size = 10000, replace = TRUE))
data$value[data$Type == "b"] <- data$value[data$Type == "b"] +
    rnorm(sum(data$Type == "b"), mean = 55)

gp <- ggplot(data = data, aes_string(x = "value"))
gp <- gp + geom_density(aes_string(fill = "Type"), alpha = 0.3)

vlines <- data.frame(value = c(mean(data$value[data$Type == "a"]),
                               mean(data$value[data$Type ==  "b"])), 
                     Mean = c("A", "B"))

gp2 <- gp + geom_vline(data = vlines, aes(xintercept = value, colour = Mean),
                       size = 1.05, linetype = "dashed", show.legend = TRUE)
gp3 <- gp2 + geom_vline(xintercept = (50 + 55 + 50) / 2, size = 1.05)

gp3

Upvotes: 2

Views: 662

Answers (1)

alistaire
alistaire

Reputation: 43354

You can pass the order parameter of guide_legend passed to the guide parameter of the scale_* functions for the guides you want to rearrange. For example:

library(ggplot2)
set.seed(1234)

data <- data.frame(value = rnorm(n = 10000, mean =50, sd = 20),
                   Type = sample(letters[1:2], size = 10000, replace = TRUE))
data$value[data$Type == "b"] <- data$value[data$Type == "b"] +
    rnorm(sum(data$Type == "b"), mean = 55)

vlines <- data.frame(value = c(mean(data$value[data$Type == "a"]),
                               mean(data$value[data$Type ==  "b"])), 
                     Mean = c("A", "B"))

ggplot(data, aes(x = value)) + 
    geom_density(aes(fill = Type), alpha = 0.3) + 
    geom_vline(data = vlines, aes(xintercept = value, colour = Mean),
               size = 1.05, linetype = "dashed", show.legend = TRUE) + 
    geom_vline(xintercept = (50 + 55 + 50) / 2, size = 1.05) + 
    scale_fill_discrete(guide = guide_legend(order = 1)) +    # fill first
    scale_color_discrete(guide = guide_legend(order = 2))     # color second

ggplot(data, aes(x = value)) + 
    geom_density(aes(fill = Type), alpha = 0.3) + 
    geom_vline(data = vlines, aes(xintercept = value, colour = Mean),
               size = 1.05, linetype = "dashed", show.legend = TRUE) + 
    geom_vline(xintercept = (50 + 55 + 50) / 2, size = 1.05) + 
    scale_fill_discrete(guide = guide_legend(order = 2)) +    # now fill second
    scale_color_discrete(guide = guide_legend(order = 1))     # and color first

Upvotes: 2

Related Questions