【问题标题】:Increase number of axis ticks in ggplot2 for dates增加 ggplot2 中日期的轴刻度数
【发布时间】:2015-03-10 18:00:42
【问题描述】:

我有一些时间序列数据要绘制,我想要更精细的轴刻度。例如:

library(lubridate)
library(ggplot2)
library(scales)

dat <- data.frame(date = paste0("09-01-", gsub(" ", "0", format(1:30))),
                  stringsAsFactors = FALSE)
dat$date <- ymd(dat$date)
dat$y <- rnorm(nrow(dat))

p <- ggplot(dat, aes(x = date, y = y)) + geom_point()

基于this post我试过

p  + scale_x_continuous(breaks=pretty_breaks(n=10))

但是Error: Discrete value supplied to continuous scale。关于如何做到这一点的任何想法?

R Under development (unstable) (2014-12-29 r67265)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

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

other attached packages:
[1] scales_0.2.4    ggplot2_1.0.0   lubridate_1.3.0

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4 digest_0.6.4     grid_3.2.0       gtable_0.1.2    
 [5] labeling_0.2     MASS_7.3-35      memoise_0.2.1    munsell_0.4.2   
 [9] plyr_1.8.1       proto_0.3-10     Rcpp_0.11.2      reshape2_1.4    
[13] stringr_0.6.2    tools_3.2.0  

【问题讨论】:

    标签: r ggplot2 lubridate


    【解决方案1】:

    尝试更改date 字段的类并使用scale_x_date

    dat$date <- as.Date(dat$date)
    p <- ggplot(dat, aes(x = date, y = y)) + geom_point()
    p + scale_x_date(breaks = scales::breaks_pretty(10))
    

    【讨论】:

    • 另见参数date_formatbreaks = date_breaks(...)minor_breaks(需要library(scales);见?scale_x_date)。
    • pretty_breaks() 现在是 breaks_pretty()
    猜你喜欢
    • 2017-09-23
    • 2020-02-16
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多