【问题标题】:Rearrange x-axis of hour when plotting绘图时重新排列小时的 x 轴
【发布时间】:2013-11-24 06:03:06
【问题描述】:

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

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
...

然后我用它制作了一个多线图:

library(lattice)
xyplot(intensity ~ hour, groups= grp, type= 'l', data= df)

图表如下所示:

但它不遵循人们的生命周期。我正在尝试将 0-4 小时重新定位在 x 轴的右端。有人有一些想法吗?非常感谢!

更新: 我试图将小时更改为一个因子,但输出看起来不够好:线条在 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)

【问题讨论】:

  • 您可以将时间更改为一个因子,然后使用 levels 参数对其进行排序。
  • 谢谢@TylerRinker!这听起来像是一个合理的计划,但事实证明存在一些缺陷,正如问题中更新的那样。

标签: r plot axis lattice


【解决方案1】:

为了清楚起见,这是一个使用ggplot 以及仅由两组组成的示例数据的解决方案。 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"))

现在,让我们调整一下时间尺度吧!

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

让我知道它是否有效;-)

【讨论】:

  • 非常感谢!它确实有效,我猜 lattice 出了点问题...... ggplot2 确实是一个更好的包!
猜你喜欢
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
相关资源
最近更新 更多