Achieving Smooth Curve Graphs with R
□ How to convert character to POSIXct format in R?
In my previous post, I created a curve graph like the one shown below.
df= data.frame(structure(list(time = c("2022-10-01 00:30:00", "2022-10-01 01:30:00",
"2022-10-01 02:30:00", "2022-10-01 03:30:00", "2022-10-01 04:30:00",
"2022-10-01 05:30:00", "2022-10-01 06:30:00", "2022-10-01 07:30:00",
"2022-10-01 08:30:00", "2022-10-01 09:30:00", "2022-10-01 10:30:00",
"2022-10-01 11:30:00", "2022-10-01 12:30:00", "2022-10-01 13:30:00",
"2022-10-01 14:30:00", "2022-10-01 15:30:00", "2022-10-01 16:30:00",
"2022-10-01 17:30:00", "2022-10-01 18:30:00", "2022-10-01 19:30:00",
"2022-10-01 20:30:00", "2022-10-01 21:30:00", "2022-10-01 22:30:00",
"2022-10-01 23:30:00"),
solar_radiation = c(0, 0, 0, 0, 0, 0, 0, 94.8464713165497,
292.960199004975, 483.373881932022, 636.977557890442,
739.091692307692, 781.551058146702, 760.003039513678,
679.285714285714, 542.340616966581, 365.719847651291,
169.117233294256, 11.3918975358485, 0, 0, 0, 0, 0)),
class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA, -24L)))
df$time=as.POSIXct(df$time)
ggplot(data=df, aes(x=time, y=solar_radiation)) +
geom_line () +
scale_x_datetime(date_breaks="4 hour", date_labels="%H:%M") +
scale_y_continuous(breaks=seq(0,1500,500), limits = c(0,1500)) +
labs(x="Hour", y=bquote("PAR (μ mol "~m^-2*~s^-1*")")) +
theme_classic(base_size=18, base_family="serif")+
theme(axis.line=element_line(linewidth=0.5, colour="black"))
The curve on the graph appears to be not very smooth, and I want to make it smoother. Therefore, I will add geom_smooth()
, but the method will be method="gam"
ggplot(data=df, aes(x=time, y=solar_radiation)) +
geom_smooth (method="gam", formula=y~s(x, k=13), se=FALSE) +
scale_x_datetime(date_breaks="4 hour", date_labels="%H:%M") +
scale_y_continuous(breaks=seq(0,1500,500), limits = c(0,1500)) +
labs(x="Hour", y=bquote("PAR (μ mol "~m^-2*~s^-1*")")) +
theme_classic(base_size=18, base_family="serif")+
theme(axis.line=element_line(linewidth=0.5, colour="black"))
code summary: https://github.com/agronomy4future/r_code/blob/main/Achieving_Smooth_Curve_Graphs_with_R.ipynb
© 2022 – 2023 https://agronomy4future.com