格式化ggplot2图例中的缩进

时间:2016-04-04 16:11:31

标签: r ggplot2 format legend

在这个情节的图例中,我希望“Box”和“ID”与左边距相同。你能给我一些关于怎么做的提示吗?非常感谢!

# Load packages and data    
library(ggplot2)

ID <- c(rep(1, 10), rep(2, 10))
Box <- c(rep("Red", 5), rep("Blue", 5), rep("Red", 5), rep("Blue", 5))
Time <- c(seq(1, 5), seq(1, 5), seq(1, 5), seq(1, 5))
Value <- runif(20, min=10, max=30)
dd <- data.frame(ID, Box, Time, Value)

# Plot
p1 <- ggplot(data = dd,
             aes(x = Time, y = Value, 
                 group = interaction(ID, Box),
                 shape = as.factor(ID),
                 colour=as.factor(ID),
                 linetype=Box)) +
  geom_point(size = 3.5) +
  geom_line() +
  scale_colour_grey(start = 0, end = 0.5, name = "ID",
                    labels = c("1", "2")) +
  scale_shape_discrete(name = "ID",
                       labels = c("1", "2")) +
  scale_linetype_discrete(name = "Box", 
                          labels = c("Red", "Blue")) +
  theme_bw() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        aspect.ratio = 1, 
        text = element_text(size = 20),
        legend.position = c(0, 1), 
        legend.justification = c(0, 1),
        legend.key = element_blank())
plot(p1)

1 个答案:

答案 0 :(得分:1)

I think you simply need to add legend.box.just = 0 in theme().