在ggplot2中添加手动图例

时间:2018-10-15 02:41:10

标签: r ggplot2 legend

您好,我难以在ggplot2中添加图例

我的代码在这里。

a <- rnorm(120)
b <- runif(120)
c <- rep(c("a","b","c"),40)
d0 <- as.POSIXct(  "2017-01-01 00:00:00",  format="%Y-%m-%d %H:%M:%S")
datetime <- d0 + seq(  from=0,  to=(3600*24*(5)-3600),  by=3600)

sample <- data.frame(a,b,c,datetime)

p1<-  ggplot(sample, aes(x=datetime)) +   
  geom_point(aes(y=a)) + 
  geom_smooth(aes(y=a)) +
  geom_line(aes( y=b),colour='red') + 
  scale_y_continuous(sec.axis = sec_axis(~., name = "b")) +
  facet_wrap(~c)

p1 +legend????

谢谢

1 个答案:

答案 0 :(得分:2)

library(hrbrthemes)
library(ggplot2)

# reproducible
set.seed(2018-10-14)

data.frame(
  a = rnorm(120),
  b = runif(120),
  c = rep(c("a","b","c"), 40),
  datetime = as.POSIXct("2017-01-01 00:00:00",  format="%Y-%m-%d %H:%M:%S") +
    seq(from=0,  to=(3600*24*(5)-3600),  by=3600),
  stringsAsFactors = FALSE
) -> smpl

ggplot(smpl, aes(x=datetime)) +   
  geom_point(aes(y=a)) + 
  geom_smooth(aes(y=a)) +
  geom_line(aes(y=b, colour='thing i want as a legend')) + 
  scale_y_continuous(sec.axis = sec_axis(~., name = "b")) +
  scale_color_manual(
    name = "An informative legend name",
    values = c('thing i want as a legend' = "red")
  ) +
  guides(
    colour = guide_legend(title.position = "top")
  ) +
  facet_wrap(~c) +
  theme_ipsum_rc(grid="XY") +
  theme(legend.position = "bottom")

enter image description here