R语言时间序列绘图求助:按日轴展示多月份/季节径流与气候数据
Hey Sascha, I noticed a small but critical date parsing issue in your initial code first—let's fix that before diving into your plotting goals, since accurate date handling is the foundation for all the analysis that follows. Then we'll tackle your two main challenges step by step:
Key Fix: Correct Date Parsing
Your raw outflow data uses the dd.mm.yyyy format (e.g., 03.12.2012), but your original code tried to parse it with %Y-%m-%d (year-month-day). This would fail to create a valid xts object. Let's fix that first:
# Load required packages (install if missing: install.packages(c("xts", "lubridate", "ggplot2", "dplyr"))) library(xts) library(lubridate) library(ggplot2) library(dplyr) # Fix outflow date parsing outflow$datum <- as.Date(outflow$datum, format = "%d.%m.%Y") # Create valid xts object and calculate daily means outflow.xts <- xts(outflow$liter_s, order.by = outflow$datum) outflow.xts <- apply.daily(outflow.xts, mean, na.rm = TRUE) # Convert to dataframe for easier plotting outflow.df <- data.frame( date = index(outflow.xts), liter_s = coredata(outflow.xts), month = lubridate::month(date, label = TRUE), # Get month abbreviations (Jan, Feb, etc.) day_of_month = lubridate::day(date) # Extract day of the month (1-31) )
1. Plot Multi-Month Runoff with Day-of-Month X-Axis
To plot all months on a single graph with only day-of-month on the X-axis, we'll use ggplot2 to group data by month (colored for distinction) and map day_of_month to the X-axis. This lets you compare runoff patterns across months directly:
ggplot(outflow.df, aes(x = day_of_month, y = liter_s, color = month)) + geom_point(alpha = 0.6, size = 2) + # Scatter points for individual daily values geom_smooth(method = "loess", se = FALSE, linewidth = 1) + # Optional trend line to highlight patterns labs( x = "Day of Month", y = "Runoff (liter/s)", color = "Month", title = "Runoff Variation by Day of Month Across All Months" ) + theme_minimal() + scale_x_continuous(breaks = seq(1, 31, 5)) # Adjust X-axis ticks to your preference
- The
color = monthargument ensures each month’s data is plotted in a unique color. - Use
geom_line()instead ofgeom_point()if you prefer to connect daily values (better for continuous time series).
2. Plot Seasonal Runoff Subsets with Corresponding Climate Data
First, we'll align your runoff and climate data by date, then extract seasonal subsets. We'll cover two common visualization approaches: a faceted plot (clearer for comparison) and a dual-Y axis plot (side-by-side trend view).
Step 1: Prepare Seasonal Subsets
# Add season labels to climate data klimadaten <- klimadaten %>% mutate( season = case_when( month(datum) %in% c(6,7,8) ~ "Summer", month(datum) %in% c(12,1,2) ~ "Winter", month(datum) %in% c(3,4,5) ~ "Spring", TRUE ~ "Autumn" ) ) # Extract summer runoff (matches your existing code) summer_runoff <- outflow.xts[.indexmon(outflow.xts) %in% c(5,6,7)] # Note: .indexmon uses 0-based index (Jun=5, Jul=6, Aug=7) summer_runoff_df <- data.frame( date = index(summer_runoff), liter_s = coredata(summer_runoff), season = "Summer" ) # Extract matching summer climate data summer_climate <- klimadaten %>% filter(season == "Summer") # Merge runoff and climate data by date (only keep matching dates) summer_combined <- inner_join(summer_runoff_df, summer_climate, by = "date")
Step 2: Visualization Option 1 – Faceted Plot (No Dual Y-Axis)
This is the recommended approach for clarity, as dual Y-axes can be misleading:
# Reshape data to long format for faceting summer_combined_long <- summer_combined %>% pivot_longer( cols = c(liter_s, precipitation), # Replace "precipitation" with your actual climate column name names_to = "variable", values_to = "value" ) ggplot(summer_combined_long, aes(x = date, y = value, color = variable)) + geom_line(linewidth = 1) + facet_wrap(~variable, scales = "free_y", ncol = 1) + # Separate panels with independent Y-axes labs( x = "Date", y = "Value", color = "Variable", title = "Summer Runoff vs. Precipitation" ) + theme_minimal() + scale_color_manual(values = c("liter_s" = "navy", "precipitation" = "forestgreen"))
Step 2: Visualization Option 2 – Dual Y-Axis Plot
If you prefer to see both variables on one axis, use this (adjust the scaling factor to match your data ranges):
# Calculate scaling factor to align precipitation with runoff range scaling_factor <- max(summer_combined$liter_s) / max(summer_combined$precipitation) ggplot(summer_combined, aes(x = date)) + geom_line(aes(y = liter_s, color = "Runoff"), linewidth = 1) + geom_line(aes(y = precipitation * scaling_factor, color = "Precipitation"), linewidth = 1) + scale_y_continuous( name = "Runoff (liter/s)", sec.axis = sec_axis(~./scaling_factor, name = "Precipitation (mm)") # Reverse scaling for the second axis ) + labs( x = "Date", color = "Variable", title = "Summer Runoff vs. Precipitation" ) + theme_minimal() + scale_color_manual(values = c("Runoff" = "navy", "Precipitation" = "forestgreen"))
内容的提问来源于stack exchange,提问作者Sascha

