简体   繁体   English

绘制时重新排列小时的x轴

[英]Rearrange x-axis of hour when plotting

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. 我正在尝试将0-4时移到x轴的右端。 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. 更新:我试图将小时更改为一个因子,但输出效果看起来不够好:这些行在2300-0000之间被截断,并且在六个行旁边没有其他三个平行的“基准”。

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)

在此处输入图片说明

Here's a solution using ggplot along with sample data consisting of only two groups for reasons of clarity. 为了清楚起见,这是一个使用ggplot以及仅包含两组数据的示例数据的解决方案。 The approach using the levels argument from the factor function suggested by Tyler Rinker is absolutely right. 使用Tyler Rinker建议的factor函数中的levels参数的方法是绝对正确的。

# 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM