问题
I have a record of activities by six groups of people which looks like this:
grp hour intensity
1 0 0.048672391
2 0 0.264547556
3 0 0.052459840
4 0 0.078953270
5 0 0.239357060
6 0 0.078163513
1 1 0.029673036
2 1 0.128206479
3 1 0.030184495
4 1 0.076848385
5 1 0.061325717
6 1 0.039264419
1 2 0.020177515
2 2 0.063696611
3 2 0.023759638
4 2 0.047865380
5 2 0.030226285
6 2 0.021652375
...
and I make a multiple-line graph out of it:
library(lattice)
xyplot(intensity ~ hour, groups= grp, type= 'l', data= df)
The graph looks like this:

but it doesn't follow people's life cycle. I'm trying to relocate hour 0-4 at the right end of x-axis. Anybody with some ideas? Thanks a lot!
Update: I tried to change hour to a factor but the output didn't look good enough: the lines are cut off between 2300 - 0000 and there are three parallel 'baselines' out of no where beside the six lines.
df$hour <- as.factor(df$hour)
hourder <- levels(df$hour)
df$hour <- factor(df$hour, levels= c(hourder[6:24], hourder[1:5]))
xyplot(intensity ~ hour, groups= grp, type= 'l', data= df)

回答1:
Here's a solution using ggplot
along with sample data consisting of only two groups for reasons of clarity. The approach using the levels
argument from the factor
function suggested by Tyler Rinker is absolutely right.
# Required packages
library(ggplot2)
# Initialize RNG
set.seed(10)
# Sample data
df <- data.frame(
grp = as.character(rep(1:2, 24)),
hour = rep(0:23, each = 2),
intensity = runif(2 * 24, min = 0, max = .8)
)
# Plot sample data
ggplot(aes(x = hour, y = intensity, group = grp, colour = grp), data = df) +
geom_line() +
labs(x = "Time [h]", y = "Intensity") +
scale_color_manual("Groups", values = c("1" = "red", "2" = "blue"))

Now, let's adjust the time scale!
# Now, reorder your data according to a given index
index <- c(5:23, 0:4)
df$hour <- factor(df$hour, levels = as.character(index), ordered = T)
# Plot sample data with reordered x-axis
ggplot(aes(x = hour, y = intensity, group = grp, colour = grp), data = df) +
geom_line() +
scale_color_manual("Groups", values = c("1" = "red", "2" = "blue"))

Let me know if it works ;-)
来源:https://stackoverflow.com/questions/20171654/rearrange-x-axis-of-hour-when-plotting