добавить легенду в ggplot2 - PullRequest
       8

добавить легенду в ggplot2

0 голосов
/ 15 октября 2018

Привет, я борюсь с добавлением легенды в 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 голосов
/ 15 октября 2018
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

...