R语言中axis.POSIXct设置时间X轴无效的求助
Hey there! Let's get your x-axis showing those hourly 00:00 to 23:59 ticks properly. The main problem with your current code is that your FILENAME column is a factor (categorical data), not a proper datetime object. axis.POSIXct only works when your x-axis is a POSIXct datetime—so we need to first extract and convert the time from your filenames, then rebuild the plot.
Step 1: Extract Datetime from FILENAME
First, we'll pull the timestamp out of each filename string and convert it to a POSIXct datetime. You can use base R or the stringr package for this:
Option 1: Base R (no extra packages)
# Extract the datetime substring from each filename V40VH_20171115_ACI$datetime <- sub(".*(2017-11-15_\\d{2}-\\d{2}-\\d{2}).*", "\\1", V40VH_20171115_ACI$FILENAME) # Convert the string to POSIXct datetime V40VH_20171115_ACI$datetime <- as.POSIXct(V40VH_20171115_ACI$datetime, format = "%Y-%m-%d_%H-%M-%S")
Option 2: Using stringr (cleaner syntax)
If you have stringr installed, this is more readable:
library(stringr) # Extract the datetime pattern from filenames V40VH_20171115_ACI$datetime <- str_extract(V40VH_20171115_ACI$FILENAME, "2017-11-15_\\d{2}-\\d{2}-\\d{2}") # Convert to POSIXct V40VH_20171115_ACI$datetime <- as.POSIXct(V40VH_20171115_ACI$datetime, format = "%Y-%m-%d_%H-%M-%S")
Step 2: Plot with Proper Time Axis
Now that we have a datetime column of POSIXct type, we can plot it and use axis.POSIXct to get your hourly ticks:
# Create the plot with datetime as x-axis plot(V40VH_20171115_ACI$datetime, V40VH_20171115_ACI$MEAN, axes = FALSE, ylab = "ACI", xlab = "Hour", pch = 16, col = "darkred") # Optional: Style points for visibility # Add y-axis (unchanged from your code) axis(2, labels = TRUE) # Add x-axis with hourly ticks (00:00 to 23:59) axis.POSIXct(1, at = seq(from = as.POSIXct("2017-11-15 00:00:00"), to = as.POSIXct("2017-11-15 23:59:59"), by = "hour"), format = "%H:%M") # Shows "00:00", "01:00", etc. # Add a box around the plot box() # Optional: Add a title if you want title(main = "ACI Over 2017-11-15")
Why Your Original Code Didn't Work
When you plotted FILENAME (a factor), R treated the x-axis as integer values (1, 2, 3...) corresponding to the factor levels—not actual time values. Your axis.POSIXct code was trying to add ticks for times like 00:00, which are way outside the x-axis range of 1 to nrow(data). By converting to POSIXct, R recognizes the x-axis as a time scale, so axis.POSIXct can correctly place the hourly ticks.
内容的提问来源于stack exchange,提问作者Saskia

