R绘图前两年的月份 [英] R plot months for the first 2 years

查看:153
本文介绍了R绘图前两年的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不同对象的数据最多2年的数据框架:

  ISBN日期数量
3457 2004-06-15 10
3457 2004-08-16 6
3457 2004-08-19 10
3457 2005-04-19 7
3457 2005-04-20 12
9885 2013-01-15 10
9885 2013-03-16 6
9855 2013-08-19 10
9885 2014-09-19 7
9885 2014-09-20 12

如何绘制 Jan至Dec 第一年,继续 1月至12月第2年
我想这个想法是使年龄正常化(有第一,第二),但不是几个月。 (这里是一个例子)


I have a data frame with data for max 2 years period on different objects:

ISBN   Date        Quantity
3457   2004-06-15  10
3457   2004-08-16  6
3457   2004-08-19  10
3457   2005-04-19  7
3457   2005-04-20  12
9885   2013-01-15  10
9885   2013-03-16  6
9855   2013-08-19  10
9885   2014-09-19  7
9885   2014-09-20  12

How can I plot Jan to Dec for the 1st year, continued by Jan to Dec for the 2nd year? I guess the idea is to normalize the years (to have 1st, 2nd), but not the months. (here's an example) Number of Items Sold over 2 Years Period Since Release

解决方案

You could try:

data <- df %>%
  group_by(ISBN) %>%
  arrange(Date) %>%
  mutate(Year  = year(Date), 
         Month = month(Date, label = TRUE),
         Rank  = paste(sapply(cumsum(Year != lag(Year,default=0)), toOrdinal), "Year")) %>%
  group_by(Rank, Month, add = TRUE) %>%
  summarise(Sum = sum(Quantity))

ggplot(data = data, aes(x = Month, y = Sum, 
                        group = factor(ISBN), 
                        colour = factor(ISBN))) +
  geom_line(stat = "identity") +
  facet_grid(. ~ Rank) +
  scale_colour_discrete(name = "ISBN") +
  theme(panel.margin = unit(0, "lines"),
        axis.text.x = element_text(angle = 90))


Aussming the following df:

df <- data.frame(
  ISBN = sample(c(3457, 9885), 1000, replace = TRUE),
  Date = sample(seq(as.Date('2004/01/01'), 
                    as.Date('2011/12/31'), by = "month"), 
                1000, replace = TRUE),
  Quantity = sample(1:12, 1000, replace = TRUE)
)

This would produce:

这篇关于R绘图前两年的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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