如何彻底移除ggplot()绘图时检测到的33行含缺失值的数据?
Great question! Let's break this down step by step:
First, let's clarify what's behind that ggplot warning:
When you see Warning message: Removed 33 row(s) containing missing values (geom_path), ggplot is removing rows where any of the variables you mapped to geom_path have NA values—not just rows that are entirely NA. For example, if you plotted with aes(x = date, y = measurement), any row where date OR measurement is NA gets filtered out for the path plot, even if your other 5 dataset variables have valid data. Full-NA rows would also be included in this count if they have NA in the mapped variables, but partial-NA rows (for the plot-specific variables) are the primary reason for the warning here.
Now, to permanently remove those 33 rows from your dataset, you'll want to filter out exactly the rows ggplot excluded. Here are a few straightforward methods:
1. Base R approach (target plot variables)
Suppose your dataset is named my_data, and the variables used in your geom_path mapping are x_var and y_var. You can keep only rows where both variables are non-NA:
my_data_clean <- my_data[!is.na(my_data$x_var) & !is.na(my_data$y_var), ]
2. Using complete.cases() for multiple plot variables
If you mapped additional variables (like color or size) to geom_path, you can target all relevant columns with complete.cases():
# Replace with your actual plot-related variable names plot_vars <- c("x_var", "y_var", "group_var") my_data_clean <- my_data[complete.cases(my_data[, plot_vars]), ]
3. Tidyverse/dplyr approach (cleaner syntax)
If you use the tidyverse ecosystem, this readable syntax makes it easy to extend for more variables:
library(dplyr) my_data_clean <- my_data %>% filter( !is.na(x_var), !is.na(y_var) # Add more lines here for any other variables used in geom_path's aes() )
Verify you've removed the correct rows
To confirm you've excluded exactly 33 rows, check the row count difference:
cat("Rows removed:", nrow(my_data) - nrow(my_data_clean), "\n")
This should print Rows removed: 33 if you've targeted the right variables.
内容的提问来源于stack exchange,提问作者Sophie Allan

