首页 文章

R中条形图中x轴上的日期

提问于
浏览
0

我是R的新手 . 到目前为止,我一直试图完成这项任务,但我没有成功 . 我需要在x轴上生成带有日期的条形图(格式为月(数字) - 年) . 我有36个数据 .

2010 01    20  
2010 02    29 

2010 03    24    
2010 04    10

2010 05    14    
2010 06    19    
2010 07    25    
2010 08    30     
2010 09    36    
2010 10    34    
2010 11    34     
2010 12    25    
2011 01    27     
2011 02    48     
2011 03    79    
2011 04    76    
2011 05    58    
2011 06    56   
2011 07    65    
2011 08    66    
2011 09   120    
2011 10   126    
2011 11   139    
2011 12   109     
2012 01    94    
2012 02    48    
2012 03    87    
2012 04    86    
2012 05    97  
2012 06    92    
2012 07   100     
2012 08    95  
2012 09    94    
2012 10    77   
2012 11    88    
2012 12    57

第一列是第二个月,第二个月,第三个是本月的太阳黑子数 .

我需要在y轴上生成带有多个太阳黑子的条形图,并在x轴上生成日期 .

1 回答

  • 0

    我们可以 paste 'year'和'month'列并使用 library(zoo)library(zoo) 创建'yearmon' Class对象 . 使用'YearMon'设置数据集的第三列的名称,并使用 barplot 绘图 .

    library(zoo)
    YearMon <- as.yearmon(with(df1, paste(year, month)), '%Y %m')
    barplot(setNames(df1[,3], YearMon))
    

    如果您需要 %m-%Yformat 'YearMon'格式的'x axis'标签,并在 names.arg 中指定它 .

    barplot(df1[,3], names.arg=format(YearMon, '%m-%Y'))
    

    数据

    df1 <- structure(list(year = c(2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 
    2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 
    2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 
    2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 
    2012L, 2012L, 2012L), month = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 
    9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 
    12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), number = c(20L, 
    29L, 24L, 10L, 14L, 19L, 25L, 30L, 36L, 34L, 34L, 25L, 27L, 48L, 
    79L, 76L, 58L, 56L, 65L, 66L, 120L, 126L, 139L, 109L, 94L, 48L, 
    87L, 86L, 97L, 92L, 100L, 95L, 94L, 77L, 88L, 57L)), .Names = c("year", 
    "month", "number"), class = "data.frame", row.names = c(NA, -36L))
    

相关问题