如何使用特定选项绘制时序图

问题描述 投票:0回答:1

我有这个data.table有3列。第一个是关于MonthlySalesMean,第二个是年份,然后是月份。

> data[,MonthlySalesMean:=mean(StoreMean),by=c("DateMonth","DateYear")][,c("MonthlySalesMean","DateYear","DateMonth")]
        MonthlySalesMean DateYear DateMonth
     1:         6839.340     2015         7
     2:         6839.340     2015         7
     3:         6839.340     2015         7
     4:         6839.340     2015         7
     5:         6839.340     2015         7
    ---                                    
641938:         6852.171     2013         1
641939:         6852.171     2013         1
641940:         6852.171     2013         1
641941:         6852.171     2013         1
641942:         6852.171     2013         1

我需要绘制三行图,因为我有3年:

> unique(data[,DateYear])
[1] 2015 2014 2013
> 

对于每年或每一行,应在一年中的所有月份绘制MonthlySalesMean值。换句话说,它应该像这个图:

enter image description here

我该怎么办呢?谢谢你提前!

r ggplot2
1个回答
1
投票

如果没有可重复的示例,我无法测试您的数据,但这是一个想法。您绘制一条路径,销售美学(y)与月份(x)按年份(颜色)分组

library(tidyverse)

example_data <- tibble(
  MonthlySalesMean = rnorm(36, 100, 20),
  DateYear = c(rep(2013, 12), rep(2014, 12), rep(2015, 12)),
  DateMonth = c(1:12, 1:12, 1:12)
)


ggplot(example_data, aes(x = DateMonth, y = MonthlySalesMean, color = as.factor(DateYear))) + 
  geom_path() + 
  geom_point(size = 2) + 
  geom_text(aes(label = DateYear),
            data = filter(example_data, DateMonth == 1),
            nudge_x = -0.5) + # plot year numbers 
  scale_x_continuous(breaks = 1:12, labels = month.abb) +
  scale_colour_manual(guide = FALSE,  # hides legend
                      values  = c("red", "green", "blue")) + # custom colors
  expand_limits(x = 0.5) + # adds a space before January
  labs(x = "Month", y = "Sales") + 
  theme_bw() +
  theme(panel.grid = element_blank()) # removes gridlines

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.