Astrid Sanna
Astrid Sanna

Reputation: 1

ggplot legend for timeseries showing multiple variables and geometries

I'm trying to add a legend to this timeseries and rename each y in the legend. I did some research and I couldn't find an example that fit my case. Each geom_ correspond to a column in my df_07 (containing only integers).

here is my code:

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

I'm trying to create a legend that looks like this: "blue line" Fitted monitor PM25
"dashed line" Monitor PM25 "empty circle" Sensor PM25

Thank you so much!

Upvotes: 0

Views: 188

Answers (1)

Sirius
Sirius

Reputation: 5429

When you run into more complex legends I find that ggplot often ends up working against you. Here is a solution based on regular plot functions:


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

old fashioned plot

Upvotes: 1

Related Questions