简体   繁体   中英

add manual legend in ggplot2

Hi im struggling with adding legend in ggplot2

my code is here.

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????

Thanks

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM