【问题标题】:add manual legend in ggplot2在 ggplot2 中添加手动图例
【发布时间】:2018-10-15 02:41:09
【问题描述】:

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

谢谢

【问题讨论】:

  • 您是否有不想正确映射美学的原因?

标签: r ggplot2 legend


【解决方案1】:
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")

【讨论】:

    猜你喜欢
    • 2014-11-20
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多