在R中绘制多个时间序列,具有相同的x轴值,但时间在数据框中混合。

3
我正在尝试绘制以下数据框,其中有三个不同的时间序列(由user0、user1和user2标识)。每行都有一个用户标识符、日期和一个值。请注意,保留HTML标记。
> df
   userId       date steps
1   user0 2016-03-24   794
2   user0 2016-03-25   562
3   user0 2016-03-26   682
4   user0 2016-03-27   722
5   user0 2016-03-28   883
6   user1 2016-03-24  3642
7   user1 2016-03-25  3776
8   user1 2016-03-26  3585
9   user1 2016-03-27  3585
10  user1 2016-03-28  3471
11  user2 2016-03-24  5959
12  user2 2016-03-25  5933
13  user2 2016-03-26  5802
14  user2 2016-03-27  6094
15  user2 2016-03-28  5903
> dput(df)
structure(list(userId = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("user0", "user1", 
"user2"), class = "factor"), date = structure(c(16884, 16885, 
16886, 16887, 16888, 16884, 16885, 16886, 16887, 16888, 16884, 
16885, 16886, 16887, 16888), class = "Date"), steps = c(794L, 
562L, 682L, 722L, 883L, 3642L, 3776L, 3585L, 3585L, 3471L, 5959L, 
5933L, 5802L, 6094L, 5903L)), .Names = c("userId", "date", "steps"
), row.names = c(NA, -15L), class = "data.frame")

我希望能够绘制所有时间序列(由userId字段标识)并使用不同颜色,并将日期作为x轴。我尝试了以下代码,但是您可以看到,日期在x轴上被重复显示。
plot(df$steps, axes=F, xlab="", ylab="Steps", ylim=c(0,max(df$steps)))
axis(2)
axis(1, at = seq_along(df$date), labels = df$date, las = 2, cex.axis = 0.70)
box()

此处输入图片描述

我看了其他帖子,例如"在R中绘制多条线(数据系列),每个线的颜色唯一"和"使用ggplot在同一个图上绘制多个时间序列",但它们并没有我的问题,即时间变量与其他数据混合在一起。

求解使用彩色线条的解决方案,无论是使用ggplot还是不使用都可以。

2个回答

3

这是一个基于 R 的版本:

plot(0, 0, type = "n", xlim = range(df$date), ylim = c(0, max(df$step)), axes = FALSE, xlab = "", ylab = "steps")
axis(2, las = 1)
axis(1, at = df$date, labels = df$date, las = 2, cex.axis = 0.70)
box()

cols <- c("red", "green", "blue")
for (i in 1:length(unique(df$userId)))
  with(df[df$userId == unique(df$userId)[i], ], lines(date, steps, col = cols[i]))

enter image description here


2

使用ggplot:

library(ggplot2)
ggplot(df, aes(x = date, y = steps, colour = userId)) + geom_line()

日期为x轴的三条线的图表


一个等效的(但仍然相当丑陋)基本R版本需要更多的工作:

plot(0, type = 'n', axes = FALSE, xlab = 'date', ylab = 'steps',
     xlim = c(min(df$date), max(df$date)), 
     ylim = c(min(df$steps) - 100, max(df$steps) + 100))
axis.Date(1, df$date, format = '%F')    # `axis.Date` is helpful here
axis(2, seq(0, max(df$steps + 500), 500))
box()
lapply(split(df, df$userId), function(x){lines(x$date, x$steps, 
                                               col = as.numeric(substr(x$userId, 5, 5)) + 1)})
# `paste` extra space to align legend correctly...*sigh*
legend('bottomright', paste(levels(df$userId), '   '), col = 1:3, lty = 1)

基本 R 多行图

请注意,它需要进行一些微调。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接