문제

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:

enter image description here

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)

enter image description here

도움이 되었습니까?

해결책

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"))

regular_time

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"))

shifted_time

Let me know if it works ;-)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top