23

私のデータフレームは z:

library(ggplot2); library(scales)
z <-     structure(list(Month = structure(c(14975, 15095, 15156, 15187, 
15248), class = "Date"), Value = c(1, 1, 1, 6, 1)), .Names = c("Month", 
"Value"), row.names = c(NA, 5L), class = "data.frame")


ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3,  stat="identity", position="identity") +
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(breaks = "1 month", labels=date_format("%b-%Y"))

これは問題なく動作しますが、2011 年 1 月 1 日から 2013 年 1 月 1 日までのデータ範囲が気に入っています。私の例の日付は 1/12011 から 10/1/2011 です。ggplotで2011年1月1日から2013年1月1日までの日付範囲を強制する簡単な方法はありますか?

4

3 に答える 3

46

のドキュメントでは、次?scale_x_dateを含むすべての「典型的な」連続スケール引数を受け入れると述べていますlimits

library(scales)
ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3,  stat="identity", position="identity") + 
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(date_breaks = "1 month", 
                 labels=date_format("%b-%Y"),
                 limits = as.Date(c('2011-01-01','2013-01-01')))
于 2013-01-04T18:43:06.553 に答える
10

「ggplot2」に加えてscalesパッケージもロードしたことに注意してください。関数があるので、これはggplot2::xlim機能します:

  ...... + xlim(as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y") )

更新: 説明のつかない理由で反対票を獲得しました。元の質問のコードは機能しなくなりましたが、scale_x_date(.) 呼び出しを上記の xlim() 呼び出しだけに置き換えると、エラーは発生しません。

ggplot(z, aes(Month, Value)) + 
     geom_bar(fill="orange",size=.3,  stat="identity", position="identity") +
     geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
     xlim(as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y") )

ここに画像の説明を入力

于 2013-01-04T18:45:47.753 に答える