繁体   English   中英

在ggplot2中添加手动图例

[英]add manual legend in ggplot2

您好,我正在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????

谢谢

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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