2013-02-08 115 views
2

我正在繪製數據集與ggplot2中的日期,y軸是日期。我想按照時間倒序排列日期。最早的日期在y軸的頂部。另外我想以我想要的方式格式化日期。ggplot2:時間日期的反向順序

我遇到的麻煩是我相信我需要scale_y_continuous()和scale_y_reverse來完成這個任務,但是他們不能很好地一起玩。我在我的劇情我想是:

... ggplot setup ... + 
scale_y_continuous(label=function(juldate) strftime(chron(juldate), "%Y-%m-%d")) + 
scale_y_reverse() 

我得到的錯誤是:

Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale. 

我怎樣才能格式化和倒車一起工作?請注意,在這個例子中,y軸是朱利安日期整數,這是我最後一次試圖讓事情一起工作的最後一次嘗試。

獨立地,或者scale_y ...語句做它應該的,或者格式正確,或者反轉軸,但我不能同時使用兩者。

任何幫助表示讚賞。

謝謝, 馬特

新增:重複的例子,

library("ggplot2") 
library("chron") 


# Data to graph. Want to show a calendar, days on the left 
# and candle lines showing the duration of each event. 
work <- rbind(
      data.frame(ydate_start=15480, ydate_end=15489, event="Event One"), 
      data.frame(ydate_start=15485, ydate_end=15499, event="Event Two") 
      ) 


# Formats nicely, but I want order of dates reversed 
ggplot(work, 
     aes(x=event, 
      y=ydate_start, 
      ymin=ydate_start, 
      ymax=ydate_end, 
      color=event) 
) + 
    geom_linerange() + 
    ylab("Date") + 
    scale_y_continuous(label=function(x) strftime(chron(x), "%Y-%m-%d")) 


# Order reversed, but no formatting applied 
ggplot(work, 
     aes(x=event, 
      y=ydate_start, 
      ymin=ydate_start, 
      ymax=ydate_end, 
      color=event) 
) + 
    geom_linerange() + 
    ylab("Date") + 
    scale_y_reverse() 


# Both delarations don't play well together well 
ggplot(work, 
     aes(x=event, 
      y=ydate_start, 
      ymin=ydate_start, 
      ymax=ydate_end, 
      color=event) 
) + 
    geom_linerange() + 
    ylab("Date") + 
    scale_y_continuous(label=function(x) strftime(chron(x), "%Y-%m-%d")) + 
    scale_y_reverse() 
#> Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale. 
+0

請提供一個可重複使用的示例。 – 2013-02-08 20:47:55

回答

0

我解決我自己的問題。我必須有一個錯字或者沒有以某種方式正確地嘗試過,但解決方法是scale_y_reverse()將'label'作爲參數,就像scale_y_continuous一樣。以下工作:

library("ggplot2") 
library("chron") 


# Data to graph. Want to show a calendar, days on the left 
# and candle lines showing the duration of each event. 
work <- rbind(
      data.frame(ydate_start=15480, ydate_end=15489, event="Event One"), 
      data.frame(ydate_start=15485, ydate_end=15499, event="Event Two") 
      ) 


# THIS SOLVES THE PROBLEM 
ggplot(work, 
     aes(x=event, 
      y=ydate_start, 
      ymin=ydate_start, 
      ymax=ydate_end, 
      color=event) 
) + 
    geom_linerange() + 
    ylab("Date") + 
    scale_y_reverse(label=function(x) strftime(chron(x), "%Y-%m-%d"))