Skip to content
Prev 392710 / 398502 Next

Need help plotting

Hello,

Now with data, here are base R and ggplot2 plots.


b <- read.table(text=
                 "Dtime DNO2 DVOC     Dpm10    Dpm2.5 Dpm1 Mtime MNO2 
MVOC    Mpm10 Mpm2.5 Mpm1
  18:00   28  164  81.34773 24.695435   14 18:00   19  151 3.000000 
  2    1
  18:01   27  163  74.44034 23.751198   14 18:01   20  148 3.000000 
  2    1
  18:02   30  160  72.21975 22.463129   13 18:02   19  150 3.000000 
  2    1",
               header=TRUE,stringsAsFactors=FALSE)


# This base R plot needs package chron
library(chron)

# first make a real time class column
b$Dtime2 <- paste(b$Dtime, "00", sep = ":")
b$Dtime2 <- as.times(b$Dtime2)

# get the plot height and make room for
# the legend by adding 2 to y max
ylim <- range(unlist(b[c("DNO2", "MNO2")])) + c(0, 2)

# now plot one line
plot(DNO2 ~ Dtime2, b, type = "b", col = "orange", ylim = ylim)
# add the second line
points(MNO2 ~ Dtime2, b, type = "b", col = "skyblue")
# and the horizontal legend at the top center
legend("top", legend = c("DNO2", "MNO2"), horiz = TRUE,
        lty = "solid", col = c("orange", "skyblue"))


#-------

library(ggplot2)
library(dplyr)
library(tidyr)

b %>%
   mutate(Dtime = paste(Sys.Date(), Dtime),
                 Dtime = as.POSIXct(Dtime)) %>%
   select(Dtime, DNO2, MNO2) %>%
   # reshape to long format
   pivot_longer(-Dtime, names_to = "NO2") %>%
   # now plot
   ggplot(aes(Dtime, value, color = NO2)) +
   geom_line() +
   geom_point() +
   scale_color_manual(values = c("orange", "skyblue")) +
   # make datetime labels
   scale_x_datetime(date_breaks = "1 mins", date_labels = "%H:%M") +
   theme_bw()


Hope this helps,

Rui Barradas


?s 08:37 de 20/09/2022, Jim Lemon escreveu: