【问题标题】:How to plot different months as different series in the same graph in R如何在R中的同一张图中将不同的月份绘制为不同的系列
【发布时间】:2023-03-07 06:26:01
【问题描述】:

我有以下数据集

head(Data)
    Fecha PriceStats
1 01-2002    45.2071
2 02-2002    46.6268
3 03-2002    48.4712
4 04-2002    53.5067
5 05-2002    55.6527
6 06-2002    57.6684

总共有 176 个观测值。

每一行对应一个不同的月份。

我想创建一个图表,其中 x 轴为一年中的 12 个月,并且数据集的每一年(每个包含 12 个月)对应于图表中的一个系列,因此我可以绘制所有不同的年份重叠(在这种情况下为 15 系列)。

我必须在数据集上设置级别还是 ggplot 可以直接这样做?

【问题讨论】:

    标签: r graph ggplot2 levels


    【解决方案1】:

    应该这样做:

    library(ggplot2)
    library(lubridate)
    
    Data <- data.frame(date = seq(ymd('2014/01/01'), ymd('2016/12/01'), 30), 
                           n = sample(1:50, 36))
    
    Data$month <- month(Data$date)
    Data$year <- year(Data$date)
    
    ggplot(Data, aes(x = month, y = n, group = year)) + 
      geom_line(aes(colour = as.factor(year)))
    

    【讨论】:

    • 这假定您的“Fecha”列已经是日期格式。否则你将不得不转换它。使用 lubridate 的一种快速方法(但可能不是最好的方法)是:Data$Fecha
    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2012-03-20
    • 2015-10-21
    • 2021-12-11
    • 2018-01-16
    相关资源
    最近更新 更多