簡體   English   中英

ggplot逐年比較

[英]ggplot year by year comparison

我想制作一個比較不同年份獲得的數據的圖 目標是在x軸上12個月,用每年的值繪制不同的線

我正在使用的數據框是下一個:

   Month             Marg            Fiscal.Year
1  2009-04-01        20904494        2009
2  2009-05-01        43301981        2009
3  2009-06-01        14004552        2009
...
38 2012-05-01        58343271        2012
39 2012-06-01        38723765        2012
40 2012-07-01        77246753        2012

我的情節代碼是:

g <- ggplot(data = data, stat="identity", aes(x = Month, y = Marg)) + 
  geom_line() +
  geom_point() +
  geom_smooth(method = "loess") +
  scale_x_date(breaks = "1 month", labels = date_format("%b"));

但這是從2009年到2012年48個月x軸圖, 其中一行顯示了每個值(每個月的每年不同的線)。

你能幫我解決這個問題嗎? (我是R的新人,任何幫助將不勝感激)。

在此先感謝您的回答!

library(ggplot2)
# Sample data
data <- read.table(text = "Month             Marg            Fiscal.Year
                           2009-01-01        20904494        2009
                           2009-02-01        30904494        2009
                           2009-03-01        40904494        2009
                           2009-04-01        30904494        2009
                           2009-05-01        43301981        2009
                           2009-06-01        14004552        2009
                           2009-07-01        24004552        2009
                           2009-08-01        34004552        2009
                           2009-09-01        44004552        2009
                           2009-10-01        54004552        2009
                           2009-11-01        64004552        2009
                           2009-12-01        44004552        2009
                           2012-02-01        58343271        2012
                           2012-03-01        68343271        2012
                           2012-04-01        58343271        2012
                           2012-05-01        58343271        2012
                           2012-06-01        38723765        2012
                           2012-07-01        77246753        2012",
                   header=TRUE, sep="", nrows=18)
data$MonthN <- as.numeric(format(as.Date(data$Month),"%m")) # Month's number
data$Month  <- months(as.Date(data$Month), abbreviate=TRUE) # Month's abbr.

g <- ggplot(data = data, aes(x = MonthN, y = Marg, group = Fiscal.Year, colour=Fiscal.Year)) + 
     geom_line() +
     geom_point() +
     scale_x_discrete(breaks = data$MonthN, labels = data$Month)
g

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM