问题
I have tried to read through stackoverflow, blogs, books etc but have been unable to find the answer on plotting time in the x-axis in the following format(HH:MM:SS.000) in R and another quantity on the y-axis. I have the following dataset:
Time EcNo
12:54:09.000 -14.47
12:54:10.000 -17.96
12:54:11.000 -15.97
12:54:12.000 -14.61
12:54:13.000 -12.68
12:54:14.000 -10.73
12:54:15.000 -10.54
12:54:16.000 -11.62
12:54:17.000 -12.49
12:54:18.000 -11.12
How would I plot EcNo on Yaxis vs Time(x axis) in the format HH:MM:SS.000 as shown above.
I honestly would appreciate some help. many thanks
回答1:
You may also try ggplot
:
library(ggplot2)
df$time <- as.POSIXct(strptime(df$Time, format="%H:%M:%S"))
# Automatic scale selection
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point()
scale_x_datetime
is a ggplot
function, but for the nice arguments date_breaks
, and date_format
you need package scales
:
library(scales)
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("1 sec"), labels = date_format("%S"))
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("1 sec"), labels = date_format("%OS3"))
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("4 sec"), labels = date_format("%M:%S"))
回答2:
plot(strptime(dta$Time, format="%H:%M:%S"), dta$EcNo, xaxt="n")
axis(1, at=as.numeric(strptime(dta$Time, format="%H:%M:%S")),
labels=strftime( strptime(dta$Time, format="%H:%M:%S"),format="%H:%M:%S"))
回答3:
df <- data.frame(
Time=c('12:54:09.000','12:54:10.000','12:54:11.000','12:54:12.000','12:54:13.000','12:54:14.000','12:54:15.000','12:54:16.000','12:54:17.000','12:54:18.000'),
EcNo=c(-14.47,-17.96,-15.97,-14.61,-12.68,-10.73,-10.54,-11.62,-12.49,-11.12)
)
op <- options(digits.secs=3)
plot(as.POSIXct(df$Time,format="%H:%M:%OS"),df$EcNo,xaxt="n")
axis.POSIXct(1, as.POSIXct(df$Time,format="%H:%M:%OS"), format="%H:%M:%OS")
来源:https://stackoverflow.com/questions/19235466/how-do-i-plot-time-hhmmss-in-x-axis-in-r