绘制时重新排列小时的x轴 [英] Rearrange x-axis of hour when plotting

查看:61
本文介绍了绘制时重新排列小时的x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有六个人的活动记录,如下所示:

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)

图形如下:

但是它并不遵循人们的生命周期.我正在尝试将0-4时移到x轴的右端.有人有想法吗?非常感谢!

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!

更新: 我尝试将小时更改为一个因子,但输出效果看起来不够好:这些行在2300-0000之间被切断,并且除了六个行之外,还有三个平行的基准".

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)

推荐答案

为清晰起见,这是使用ggplot以及仅由两组组成的示例数据的解决方案.泰勒·林克尔(Tyler Rinker)建议使用factor函数中的levels自变量的方法是绝对正确的.

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

这篇关于绘制时重新排列小时的x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆