본문 바로가기
자료처리

ChatGPT로 R 코드 작성: 미세먼지 자료로 그래프 그리기

by Prof. Sung-Deuk Choi 2023. 10. 29.

도시대기측정소 1년 자료(1시간 간격 PM2.5 농도)로 월별 계절별 상자그림과 시간별 일별 시계열 그래프를 그리는 R 코드입니다. ChatGPT로 작성했습니다. 

 

# Install necessary packages
install.packages(c("ggplot2", "dplyr"))
library(ggplot2)
library(dplyr)

# Load data (e.g., from the data.csv file)
data <- read.csv("data.csv")

# Create date and time variable (assuming the Date_Time column contains date and time information)
data$Date_Time <- as.POSIXct(data$Date_Time, format = "%Y-%m-%d %H:%M:%S")

# Create a month variable
data$Month <- as.integer(format(data$Date_Time, "%m"))

# Create a season variable
data$Season <- ifelse(data$Month %in% c(12, 1, 2), "Winter",
                     ifelse(data$Month %in% c(3, 4, 5), "Spring",
                            ifelse(data$Month %in% c(6, 7, 8), "Summer", "Fall")))

# Change the order of the season variable
data$Season <- factor(data$Season, levels = c("Winter", "Spring", "Summer", "Fall"))

# Monthly box plot
monthly_boxplot <- ggplot(data, aes(x = factor(Month), y = PM2.5)) +
  geom_boxplot() +
  labs(title = "Monthly PM2.5 Concentration", x = "Month", y = "PM2.5 Concentration")

# Seasonal box plot
seasonal_boxplot <- ggplot(data, aes(x = Season, y = PM2.5)) +
  geom_boxplot() +
  labs(title = "Seasonal PM2.5 Concentration", x = "Season", y = "PM2.5 Concentration")

# Time series plot
time_series_plot <- ggplot(data, aes(x = Date_Time, y = PM2.5)) +
  geom_line() +
  labs(title = "Time Series of PM2.5 Concentration", x = "Date and Time", y = "PM2.5 Concentration")

# Daily average time series plot
daily_average_plot <- data %>%
  group_by(Day) %>%
  summarize(Average_PM2.5 = mean(PM2.5)) %>%
  ggplot(aes(x = Day, y = Average_PM2.5)) +
  geom_line() +
  labs(title = "Daily Average PM2.5 Concentration", x = "Day", y = "Average PM2.5 Concentration")

# Display the plots
print(monthly_boxplot)
print(seasonal_boxplot)
print(time_series_plot)
print(daily_average_plot)

 

조금 더 다듬으면 논문에도 사용할 수 있는 수준의 그림입니다. 그러나 논문에는 SigmaPlot이나 Origin Pro로 그린 더 전문적인 그림을 사용합니다. 최대한 빨리 자료 특성을 파악하기 위해서 R로 여러 그림을 그려보고 있습니다.

 

댓글