2017-10-28 39 views
1

我目前正在使用包含每個觀察值「MarketStart」的數據集。該參數的值從-24(對應於2012年1月)到47(對應於2017年10月)。數據收集始於2014年1月,因此對應於0.在R/ggplot2中將數字轉換爲月/年

我正在使用ggplot2來顯示結果,但我無法以可接受的方式標記x軸,這是我現在使用的代碼:

df <- data.frame(Name,Price,ObsMonth,Producer) 
plot.all <- 
    ggplot(data=df, aes(ObsMonth, Price, group = Name)) + 
    geom_point(alpha=0.05) + 
    geom_line() + 
    scale_x_continuous(expand = c(0, 0), limits = c(1, 36)) + 
    scale_y_continuous(expand = c(0, 0), limits = c(0, 1200)) +    
    labs(x="ObsMonth", y="Price in Euro", title="title") 

我有限的x軸的現在,但我需要的數字顯示爲日期「2012年1月,2012年2月,...,費爾南德斯2017年」今後對應於數字上面解釋的值。

EDIT1:這裏要求的是dput(DF)提供的輸出的一部分:

42L, 44L, 9L, 12L, 35L, 21L, 11L, 21L, 25L, 24L, 34L, 32L, 29L, 
41L, 36L, 33L, 30L, 43L, 44L, 31L, 39L, 35L, 27L, 42L, 23L, 28L, 
26L, 38L, 22L, 33L, 30L, 39L, 25L, 32L, 28L, 36L, 23L, 27L, 24L, 
34L, 29L, 26L, 22L, 21L, 45L, 35L, 37L, 31L, 43L, 44L, 38L, 39L, 
28L, 29L, 25L, 22L, 21L, 34L, 23L, 36L, 35L, 31L, 33L, 37L, 44L, 
26L, 30L, 27L, 24L, 27L, 25L, 29L, 28L, 26L, 30L, 31L, 31L, 30L, 
18L, 15L, 23L, 24L, 20L, 19L, 16L, 22L, 21L, 25L, 14L, 6L, 3L, 
4L, 7L, 9L, 11L, 12L, 17L, 16L, 14L, 5L, 10L, 2L, 8L, 1L, 15L, 
13L, 13L, 10L, 16L, 12L, 15L, 14L, 24L, 26L, 11L, 8L, 16L, 3L, 
6L, 13L, 12L, 29L, 19L, 4L, 1L, 9L, 17L, 25L, 28L, 7L, 18L, 10L, 
15L, 27L, 2L, 5L, 14L, 20L, 22L, 21L, 23L, 19L, 18L, 16L, 6L, 
3L, 2L, 1L, 8L, 5L, 4L, 11L, 7L, 14L, 15L, 9L, 13L, 12L, 10L, 
..... and the end part..... 
, .Names = c("Name", 
"Preis", "Erhebungsmonat", "Hersteller"), row.names = c(NA, -6732L 
), class = "data.frame") 
+0

的'lubridate'包將是有益的在這裏。你能用'dput(df)'的輸出更新你的問題嗎?請參閱[這裏](http://lubridate.tidyverse.org)瞭解更多關於該軟件包的信息。 – tyluRp

+0

感謝您的回覆tyluRp。你要求的輸出真的很長,我會編輯它的問題,並檢查你建議的包! – lilputenga

+0

嘗試更小的樣本; 'dput(head(df))' – tyluRp

回答

1

你可以一個date列添加到您的數據集。

start <- as.Date("2012-01-01") 
df$date <- seq.Date(from = start, length.out = dim(df)[1], by = "month") 

,然後改變你的情節相應

plot.all <- 
ggplot(data=df, aes(date, Price, group = Name)) + 
geom_point(alpha=0.05) + 
geom_line() + 
scale_x_continuous(expand = c(0, 0), limits = c(1, 36)) + 
scale_y_continuous(expand = c(0, 0), limits = c(0, 1200)) + 
labs(x="date", y="Price in Euro", title="title") 
+0

謝謝您的快速回復。我嘗試瞭解你所建議的方法,但我沒有得到任何有用的結果。我正在處理一個有7000多個觀測值的數據集,我基本上需要「替換」上面提到的數值,只是爲了顯示目的。如果我的數據集每月僅包含1次觀察,那麼我只能讓您的方法開始工作。 – lilputenga

+0

你可以使用'replace',參見https://stackoverflow.com/questions/11811027/replace-function-examples#11811147 如果你的數據是一個'長'格式,'ObsMonth'列的條目重複'你可以使用'rep(日期,時間= n)'。 你能提供一些數據(結構)嗎? – markus

+0

謝謝你的快速回復markus。我檢查了你提供的鏈接,我想我可以用這種方法做一個解決方法,即使我願意這樣做,否則,我認爲這仍然有效。 至於您的數據請求,我做了2個屏幕截圖: 每月觀察次數:https://prnt.sc/h39r8b 部分結構:https://prnt.sc/h39rh2 「Erhebungsmonat對應於問題中提到的「MarketStart」。 – lilputenga

相關問題