Dual-Axis Plots ggplot2 approach in R: A Step-by-Step Tutorial!

Поділитися
Вставка
  • Опубліковано 7 лют 2025
  • #DataScience #RProgramming #ggplot2 #DataVisualization #Statistics #Coding #TutorialWitness
    the power of ggplot2 for creating stunning dual-axis plots in R! This comprehensive tutorial guides you through every step of plotting with ggplot2, focusing on creating dual-axis plots that combine bar and line graphs for different data types. Perfect for researchers, data scientists, and anyone interested in enhancing their data visualization skills in R. Join us as we explore a range of ggplot2 functions, customization options, and scaling techniques to replicate a plot from the MDPI journal
    The trick is to add a secondary axis, scale the data to fit on the primary y-axis, and then scale the secondary axis according to the scale of data to be plotted on it. Difficult here to explain. Watch the video and learn how to apply that to your data.
    What You'll Learn:
    Setting up your data and necessary R packages.
    Utilizing ggplot2 for crafting a dual-axis plot.
    Customizing plot aesthetics for clear, effective data presentation.
    Practical tips for managing date formats and axis adjustments.
    code
    Load required libraries
    library(ggplot2)
    library(ggsci) # For scientific color schemes
    library(scales) # For better date formatting
    Sample data structure (replace this with your actual data)
    Rainfall = rnorm(1066,35, 40)
    data = data.frame(
    Date = seq(as.Date("2014-06-01"), as.Date("2017-05-01"), by = "day"),
    Max_Temp = runif(1066, min = 25, max = 40), # Random data for max temp
    Min_Temp = runif(1066, min = 10, max = 25), # Random data for min temp
    Rainfall = ifelse(Rainfall \greater than 0, Rainfall,0) # Random data for rainfall (range: 0 to 275 mm)
    )
    str(data)
    summary(data)
    ggplot(data,aes(x=Date))+
    geom_point(aes(y=Max_Temp, color="Max temp"))+
    geom_line(aes(y=Max_Temp, color="Max temp"))+
    geom_point(aes(y=Min_Temp, color="Min Temp"))+
    geom_line(aes(y=Min_Temp,color="Min Temp"))+
    geom_col(aes(y=Rainfall/275 *45, fill="rainfall"))+
    scale_y_continuous(name=' Maximum and minimum temperature(°c)',limits=c(0,45)
    ,sec.axis = sec_axis(~.*275/45, name="Rainfall (mm)"))+
    scale_colour_manual(values=c("Max temp"="#498ba6", "Min Temp"="#703f30"))+
    scale_fill_manual(values=c("rainfall"="darkgreen"))+
    scale_x_date(date_labels = "%Y-%m-%d", date_breaks = "1 month")+
    theme_classic()+
    theme(legend.position="top", axis.text.x = element_text(angle=90, hjust=1))+
    labs(x="",fill="",color="Temperature")
    .Facebook page:
    / rajendrachoureisc
    Mail Id:
    rajuchoure@gmail.com
    youtube playlist:
    • R programming tutorials

КОМЕНТАРІ •