R Studio - Version 2023.03.0+386 (2023.03.0+386)
I am pretty new to programming. I am trying to create a for loop that will create 10 plots using ggplot. Each plot will be from a selection from a different column in a dataset.
I am having an issue with the date format. The message 'Error: Invalid input: date_trans works with objects of class Date only' keeps coming up.
This is the code I'm running. The date format in the .csv is 'YYYY-MM-DD'.
in addition to the code below, I have also entered data$date_collected <- as.Date(data$date_collected, format("%Y,%m,%d"))
and received the same error message.
library(ggplot2)
library(dplyr)
# Read the data from CSV file
data <- read.csv("synthetic_data.csv")
# Convert "date_collected" column to proper date format
data$date_collected <- as.Date(data$date_collected)
# Specify the number of graphs to generate
num_graphs <- 10
# Loop through each graph
for (i in 1:num_graphs) {
# Select the column name and subtitle for the current graph
column_name <- paste0("gmax_", i)
subtitle <- paste0("Location ", i)
# Filter data for the specific site (GeorgetownHS) and select the 5 most recent entries
filtered_data <- data %>%
filter(Site == "GeorgetownHS") %>%
arrange(desc(date_collected)) %>%
head(5)
# Create the plot
ggplot(filtered_data, aes(x = date_collected, y = !!sym(column_name))) +
geom_line() +
geom_point() +
labs(
x = "Previous 5 Data Collection Dates",
y = "GMax Value",
title = "GMax Values",
subtitle = subtitle
) +
scale_x_date(date_labels = "%Y-%m-%d", date_breaks = "1 day") +
scale_y_continuous(limits = c(50, 120)) +
geom_hline(yintercept = 100, linetype = "dashed", color = "red") +
annotate("text", x = Inf, y = 100, hjust = 1, label = "Recommended Maximum GMax Rating")
# Save the graph as a file (optional)
ggsave(filename = paste0("graph_", i, ".png"), width = 6, height = 4, dpi = 300)
}