首页 > 解决方案 > 具有多个分类值的 ggplot 时间序列的最佳方法

问题描述

我正在使用以下数据集:

team, time, rank1, rank2, rank3, rank4, rank5
bull, 20180102,0,0,0,0,1
corn, 20180102,0,29,0,0,1
fivfo, 20180102,23,4,0,0,1
lazy, 20180102,0,0,0,0,1
tt, 20180102,0,4,222,0,1
cheer, 20180102,23,0,34,0,1
manup, 20180102,0,13,0,0,1
bull, 20180103,0,10,0,10,1
corn, 20180103,0,59,0,0,1
fivfo, 20180103,43,4,0,0,1
lazy, 20180103,0,0,0,0,1
tt, 20180103,0,4,122,0,1
cheer, 20180103,23,0,34,0,11
manup, 20180103,0,13,10,0,11

目标是在反映日期时间的同时绘制每个团队的排名。我试图使用熔化,但无法真正确定要熔化哪个轴。

我尝试按如下方式使用熔体:

melt.s <- melt(s, id=c("team","time"))
ggplot(melt.s,aes(x=time,y=value,colour=variable,group=variable)) + geom_line()

上面的问题是team名称并没有真正出现关键带走我想展示的情节是团队以及他们达到排名的时间。

试图找出最好的绘图方式,但到目前为止考虑如下

 rank5 |
 rank4 |
 rank3 |                    legend (team)
 rank2 |                     
 rank1 |___________________
        time

标签: rggplot2

解决方案


也许是这样的:

library(tidyr); library(lubridate)
gather(s, rank, rank_count, -c(team, time)) %>%
  mutate(time = ymd(time)) %>%
  ggplot(aes(time, rank_count)) +
  geom_line() +
  ggrepel::geom_text_repel(aes(label = rank_count), size = 3) +
  scale_x_date(date_labels = "%b %d") +
  facet_grid(rank~team)

在此处输入图像描述


推荐阅读