[R] Need help plotting

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Thu Sep 22 06:25:19 CEST 2022


Hello,

This type of problems generally has to do with reshaping the data. The 
format should be the long format and the data is in wide format.

Inline.

Às 23:35 de 21/09/2022, DFP escreveu:
> As I said, the lines below that you provided worked well for me. Can you 
> explain what this line does?:
> 
> # reshape to long format
>     pivot_longer(-Dtime, names_to = "NO2") %>%
> 
> -------------------------------------------------
> 
> 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") %>%


After selecting only the columns Dtime and *NO2 you need to reshape the 
data to long format. Some ways of telling pivot_longer what are the 
columns to become one are

  - explicitly writing all columns to be pivotted;
  - with negative indexing, all others will be put under the new name "NO2";
  - with a selection function such as ends_with("NO2"). This is probably 
more readable code if you return to it some time from now.


     pivot_longer(ends_with("NO2"), names_to = "NO2") %>%


With data in the long format map column NO2 to the color aesthetic and 
ggplot will automatically understand that you have 2 groups, DNO2 and 
MNO2, and plot 2 lines and 2 groups of points (one for each color) .

Hope this helps,

Rui Barradas


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



More information about the R-help mailing list