首页 > 解决方案 > 显示多个变量和几何图形的时间序列的 ggplot 图例

问题描述

我正在尝试向这个时间序列添加一个图例 并重命名图例中的每个 y 。我做了一些研究,但找不到适合我的例子。每个geom_对应于我的 df_07 中的一列(仅包含整数)。

这是我的代码:

gg07 <-
  ggplot(df_07) +
  geom_line(aes(x = datetime, y = pred_pm25_monitor_humidity), color = "blue") +
  geom_line(aes(x = datetime, y = pm25_monitor), linetype = "dashed") +
  geom_point(aes(x = datetime, y = pm25 ), shape = 1) +
  ylab("PM2.5 (µg/m3)") +
  xlab("Date") +
  ggtitle("Raw and Fitted Monitor Data -- July 01-08, 2020")

我正在尝试创建一个看起来像这样的图例:“蓝线”安装监视器 PM25
“虚线”监视器 PM25 “空圆圈”传感器 PM25

太感谢了!

标签: rggplot2plotlegend

解决方案


当您遇到更复杂的图例时,我发现 ggplot 通常最终会与您作对。这是基于常规绘图功能的解决方案:


## Create some fake data
set.seed(100)
x <- seq( 1,8, length.out=25*7 )
base.curve <- 10*(dnorm(x, mean=3.5, sd=.2) +
    dnorm(x, mean=5.2, sd=.1) +
    dnorm(x, mean=5.5, sd=2 )*3
)

library(lubridate)
a <- approx(
    c( ymd_hms('2020-07-01T00:00:00'), ymd_hms('2020-07-08T00:00:00') ),
    n = length(x)
)
x.date <- as_datetime(a$y)

pm25 <- base.curve + rnorm(length(x),sd=.4)
pm25_monitor_humidity <- base.curve^.7*.9
pm25_monitor <- pm25_monitor_humidity+rnorm(n=length(x),sd=.4)

dr <- range(x.date)
date.at <- seq(dr[1], dr[2], by="day")[seq(2,8,2)]

## Plot it:
plot( x.date, pm25, xaxt="n", type="n" )
axis( 1, at=date.at, format(date.at,"%b %d") )
points( x=x.date, y=pm25, cex=.7 )
lines( x=x.date, y=pm25_monitor_humidity, col="blue" )
lines( x=x.date, y=pm25_monitor, lty="dashed" )

## Legend:
labels <- c(
    "Sensor PM25","Fitted monitor PM25","Monitor PM25"
)
legend(
    "right",
    legend = labels,
    pch=c(1,NA,NA),
    lty=c(NA,"solid","dashed"),
    col=c("black","blue","black")
)

老式的情节


推荐阅读