geom_vline()图例的位置移位

时间:2017-04-25 07:27:01

标签: r ggplot2 legend

我有几个类似下面的情节。我的问题是geom_vline()(类型)的图例会在图表之间移动,有时会出现在“均值”图例上方,有时会出现在下方。

如何指定geom_vline()图例(或其他图例)的位置,以便我的论文中的图表没有变化?

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

1 个答案:

答案 0 :(得分:2)

您可以将传递给order的{​​{1}}参数传递给guide_legend函数的guide参数,以便重新排列指南。例如:

scale_*

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