date_breaks {scales}在ggplot中移动日期刻度 [英] date_breaks {scales} shifts date scale in ggplot

查看:68
本文介绍了date_breaks {scales}在ggplot中移动日期刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如以下示例数据集中所示,日期在2015年1月1日至2015年8月1日之间.但是,当我使用 date_breaks 函数时,x轴上的月份标签会移动.您能提出解决方案吗?

As seen in the sample dataset below, dates are between 2015-01-01 and 2015-08-01. However when I use the date_breaks function, the month labels in x-axis are shifted. Could you suggest a solution?

dfn <- read.table(header=T, text='
supp p_date length
OJ  2015-01-01  13.23
OJ  2015-03-01  22.70
OJ  2015-08-01  26.06
VC  2015-01-01   7.98
VC  2015-03-01  16.77
VC  2015-08-01  26.14
                  ')

dfn$p_date <- as.Date(dfn$p_date, "%Y-%m-%d")

library(ggplot2)
library(scales)
ggplot(dfn, aes(as.POSIXct(p_date), length, colour = factor(supp))) + 
    geom_line(size=1.3) +
    labs(colour="Lines :", x = "", y = "") +
    guides(colour = guide_legend(override.aes = list(size=5))) +  
    scale_x_datetime(breaks = date_breaks("1 months"),labels = date_format("%m/%y"))

这是我的sessionInfo

Here is my sessionInfo

> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Greek_Greece.1253  LC_CTYPE=Greek_Greece.1253    LC_MONETARY=Greek_Greece.1253 LC_NUMERIC=C                  LC_TIME=Greek_Greece.1253    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] scales_0.3.0  ggplot2_1.0.1

loaded via a namespace (and not attached):
 [1] labeling_0.3     MASS_7.3-44      colorspace_1.2-6 magrittr_1.5     plyr_1.8.3       tools_3.2.2      gtable_0.1.2     reshape2_1.4.1  
 [9] Rcpp_0.12.1      stringi_0.5-5    grid_3.2.2       stringr_1.0.0    digest_0.6.8     proto_0.3-10     munsell_0.4.2  

推荐答案

只需使用 scale_x_date 代替 scale_x_datetime :

ggplot(dfn, aes(p_date, length, colour = factor(supp))) + 
  geom_line(size=1.3) +
  labs(colour="Lines :", x = "", y = "") +
  guides(colour = guide_legend(override.aes = list(size=5))) +  
  scale_x_date(breaks = date_breaks("1 months"),labels = date_format("%m/%y"))

这篇关于date_breaks {scales}在ggplot中移动日期刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆