ggplot中NA值排序处理:服务请求散点图绘制需求
Got it, let's break down exactly how to create this service request scatter plot with ggplot2, matching all your requirements. Here's a step-by-step guide:
First, we'll read in your tab-separated data. Since empty values map to NA (as you noted), read.delim() will automatically handle those for us. We also need to make sure the request date is treated as a Date type so ggplot can sort it correctly from oldest to newest.
# Replace "your_data_file.txt" with your actual file path service_requests <- read.delim("your_data_file.txt", sep = "\t", stringsAsFactors = FALSE) # Convert request_date to Date format (adjust the format if your dates use a different pattern, e.g., "%m/%d/%Y") service_requests$request_date <- as.Date(service_requests$request_date, format = "%Y-%m-%d")
By default, ggplot will sort categorical Y-axis values from bottom to top. To get priority 1 (highest) at the top, we'll convert the priority column to an ordered factor with levels sorted from highest to lowest. NA values will be automatically excluded from the axis (since they don't map to a priority level).
# Adjust the levels to match your actual priority values (e.g., if you have 1-4 priorities, use c("1", "2", "3", "4")) service_requests$priority <- factor( service_requests$priority, levels = c("1", "2", "3"), # Highest priority first ordered = TRUE )
Now we'll use ggplot to create the plot. The X-axis will automatically sort dates from oldest to newest (since we converted to Date type), and the Y-axis will have priority 1 at the top thanks to our ordered factor.
library(ggplot2) ggplot(service_requests, aes(x = request_date, y = priority)) + geom_point(size = 3, color = "#2980b9") + # Customize size/color as needed labs( x = "Request Date", y = "Request Priority", title = "Service Request Priority Over Time" ) + theme_minimal() + scale_x_date( date_labels = "%Y-%m-%d", # Adjust date display format date_breaks = "1 day" # Change to "week" or "month" if you have more data )
Key Notes:
- NA Handling: Requests with no priority (NA) won't appear as points on the plot, which aligns with your requirement.
- Priority Levels: If your priorities are numeric instead of character, just use numeric values in the
levelsargument (e.g.,c(1,2,3)instead ofc("1","2","3")). - Date Formatting: If your input dates aren't in
YYYY-MM-DDformat, update theformatparameter inas.Date()to match your data (e.g.,"%m/%d/%Y"for MM/DD/YYYY).
内容的提问来源于stack exchange,提问作者Charles Knell

