1. okiyuki99

    Posted

    okiyuki99
Changes in title
+x軸がas.POSIXct型のときのggplotには気をつける
Changes in tags
Changes in body
Source | HTML | Preview
@@ -0,0 +1,71 @@
+
+## 結論
+- ```date_format()``` を使おう
+
+
+## だめな例1
+
+```R
+library(ggplot2)
+library(scales)
+
+# データを作る
+df1 <- data.frame(date = c(as.POSIXct("2016-01-01 10:00:00"),as.POSIXct("2016-01-02 6:00:00"),as.POSIXct("2016-01-02 23:00:00")),value = c(10,30,20))
+
+# データを確認する
+df1
+ date value
+1 2016-01-01 10:00:00 10
+2 2016-01-02 06:00:00 30
+3 2016-01-02 23:00:00 20
+
+# ggplot
+ggplot(df1,aes(x=date, y = value)) + geom_point() + scale_x_datetime(breaks = date_breaks("hour"),date_labels = "%Y-%m-%d %H") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
+
+```
+
+![Kobito.prNSCq.png](https://qiita-image-store.s3.amazonaws.com/0/69266/731c71b6-ed4b-c22b-a290-cd3a1ad29f5d.png "Kobito.prNSCq.png")
+
+
+## だめな例2
+
+```R
+# データを作る
+df2 <- data.frame(date = c(as.POSIXct("2016-01-01 10:00:00", tz="Japan"),as.POSIXct("2016-01-02 6:00:00", tz="Japan"),as.POSIXct("2016-01-02 23:00:00", tz="Japan")),value = c(10,30,20))
+
+# データを確認する
+df2
+ date value
+1 2016-01-01 10:00:00 10
+2 2016-01-02 06:00:00 30
+3 2016-01-02 23:00:00 20
+
+# ggplot
+ggplot(df2,aes(x=date, y = value)) + geom_point() + scale_x_datetime(breaks = date_breaks("hour"),date_labels = "%Y-%m-%d %H") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
+
+```
+
+![Kobito.BCqqR5.png](https://qiita-image-store.s3.amazonaws.com/0/69266/00793888-35aa-e12a-0335-0b2604fe5329.png "Kobito.BCqqR5.png")
+
+## 良い例1
+
+```R
+ggplot(df1,aes(x=date, y = value)) + geom_point() + scale_x_datetime(breaks = date_breaks("hour"), labels = date_format("%Y-%m-%d %H")) + theme(axis.text.x = element_text(angle = 45, hjust = 1))
+```
+
+![Kobito.Hl9DMX.png](https://qiita-image-store.s3.amazonaws.com/0/69266/f26d942b-1974-390f-4482-3c4fc20b4009.png "Kobito.Hl9DMX.png")
+
+
+## 良い例2
+
+```R
+ggplot(df2,aes(x=date, y = value)) + geom_point() + scale_x_datetime(breaks = date_breaks("hour"), labels = date_format("%Y-%m-%d %H", tz = "Asia/Tokyo")) + theme(axis.text.x = element_text(angle = 45, hjust = 1))
+```
+
+![Kobito.U6bvzj.png](https://qiita-image-store.s3.amazonaws.com/0/69266/eae5d991-d334-6ac9-9a7e-fa900ce82733.png "Kobito.U6bvzj.png")
+
+
+## 参考
+- [R: as.POSIXct timezone and scale_x_datetime issues in my dataset](http://stackoverflow.com/questions/36227130/r-as-posixct-timezone-and-scale-x-datetime-issues-in-my-dataset)
+- [[R] タイムゾーン変換](http://ill-identified.hatenablog.com/entry/2015/01/13/211024)
+- [R : POSIXctをas.Date() する時にtzを指定しない場合、POSIXctのタイムゾーンに何が設定されていてもUTCとみなして処理されているのでは?](http://shinya131-note.hatenablog.jp/entry/2015/12/08/200055)