使用ggplot绘制点线组合图:月度X轴与聚合值除法Y轴实现
Solution to Create Point-Line Plot with Monthly Aggregates
Let's walk through fixing your data, aggregating the values correctly, and building the plot you want step by step.
Step 1: Fix Data Creation & Cleaning
Your original data has a couple of small issues we need to address first:
- The
namecolumn isn't defined, so I'll add a dummy column for completeness. - The
anzahlcolumn contains empty strings, which we need to convert to numeric (replacing blanks withNA).
# Create reproducible test data set.seed(123) minuten <- runif(10) anzahl <- c("", "", "", "23", "", "3", "", "", "5", "56") time <- factor(c("Jan", "Jan", "Jan", "Jan", "Feb", "Feb", "Mar", "Mar", "Mar", "Apr")) name <- paste0("Item", 1:10) # Dummy name column df2 <- data.frame(name, anzahl, minuten, stringsAsFactors = FALSE) # Clean the anzahl column: convert blanks to NA and make numeric df2$anzahl <- as.numeric(gsub("^$", NA, df2$anzahl))
Step 2: Aggregate Data by Month
The key mistake in your original code is trying to calculate sums directly inside ggplot's aes()—this won't group values by month. Instead, we need to pre-aggregate the data to get the ratio of total minuten to total anzahl per month. Using dplyr makes this simple:
library(dplyr) agg_df <- df2 %>% group_by(time) %>% summarise( total_minuten = sum(minuten, na.rm = TRUE), total_anzahl = sum(anzahl, na.rm = TRUE), ratio = total_minuten / total_anzahl ) %>% # Ensure months appear in chronological order mutate(time = factor(time, levels = c("Jan", "Feb", "Mar", "Apr")))
If you don't have dplyr installed, you can use base R instead:
# Base R aggregation method total_minuten <- aggregate(minuten ~ time, data = df2, sum, na.rm = TRUE) total_anzahl <- aggregate(anzahl ~ time, data = df2, sum, na.rm = TRUE) agg_df_base <- merge(total_minuten, total_anzahl, by = "time") agg_df_base$ratio <- agg_df_base$minuten / agg_df_base$anzahl agg_df_base$time <- factor(agg_df_base$time, levels = c("Jan", "Feb", "Mar", "Apr"))
Step 3: Build the Point-Line Plot
Now use the aggregated data to create your plot with ggplot2:
library(ggplot2) ggplot(data = agg_df, aes(x = time, y = ratio, group = 1)) + geom_line(color = "#2c3e50", linewidth = 1) + # Custom line style geom_point(color = "#e74c3c", size = 3) + # Custom point style labs( x = "Month", y = "Total Minutes / Total Count", title = "Monthly Ratio of Total Minutes to Total Count" ) + theme_minimal()
Key Notes:
group = 1in theaes()is critical—it tells ggplot to connect all points into a single line (sincetimeis a factor, without this, no line will be drawn).- Pre-aggregating ensures we calculate the ratio per month, not across all rows.
- Ordering the
timefactor guarantees months show up in the correct order on the X-axis.
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

