2017-10-17 102 views
-2

我知道使用scale_x_date(date_labels="%b"...)会创建包含每月前三个字母的刻度标签。有没有办法只包括每个月的第一个字母?因此,而不是"Jan Feb March...",标签将是"J F M..."使用每月的第一个字母创建ggplot2 x轴月标签

下面是一个例子:月份标签重叠,所以我希望能够将标签更改为第一个字母。

library(lubridate) 
library(ggplot2) 


set.seed(2) 
df = data.frame(Date=seq(as.Date("2010-01-01"),as.Date("2015-12-31p 
                "), by="1 day")) 
df$value = cumsum(rnorm(nrow(df))) 


p = ggplot(df, aes(Date, value)) + 
    geom_vline(xintercept=as.numeric(df$Date[yday(df$Date)==1]), colour="grey60") + 
    geom_line() + 
    scale_x_continuous(labels = year_labels <- rep(c('J','F','M','A','M','J','J','A','S','O','N','D'),5)) + 
    theme_bw() + 
    theme(panel.grid.minor.x = element_blank()) + 
    labs(x="") 
p 

enter image description here

我试图改变线scale_x_date(date_labels="%b", date_breaks="month", expand=c(0,0))scale_x_continuous(labels = year_labels <- rep(c('J','F','M','A','M','J','J','A','S','O','N','D'),5))

但由此产生下面的错误

错误as.Date.numeric(值):“原点'必须提供

+0

可以请你提供一个可重复的例子 –

+0

你的例子是不可复制的 –

+0

我只是跳过'geom_vline(xintercept = as.numeric(df $ Date [yday(df $ Date)== 1]),color =“ grey60“)',我认为只是*装饰的一部分*,并且它工作正常 – Marco

回答

1

我找到了一个方法来做到这一点。有没有人知道更简单的方法来产生相同的输出?

set.seed(2) 
df = data.frame(Date=seq(as.Date("2010-01-01"),as.Date("2015-12-31"), by="1 day")) 
df$value = cumsum(rnorm(nrow(df))) 

year_labels <- rep(c('J','F','M','A','M','J','J','A','S','O','N','D')p,6) 


# The plot we'll start with 
p = ggplot(df, aes(Date, value)) + 
    geom_vline(xintercept=as.numeric(df$Date[yday(df$Date)==1]), colour="grey60") + 
    geom_line() + 
    # scale_x_continuous(labels = year_labels) + 
    scale_x_date("Date",breaks = c(seq(from=as.Date("2010-01-01"),to=as.Date("2015-12-31"),by="month")), 
       labels = year_labels) 
p 

enter image description here

1

我认为最好的方法是使用pretty_breaks从包装scales。它不会产生您请求的输出,但我认为更好,并且可以顺利地处理任何长度的数据。

library(ggplot2) 
library(scales) 

set.seed(2) 
df = data.frame(Date=seq(as.Date("2010-01-01"),as.Date("2014-12-31p 
               "), by="1 day")) 
df$value = cumsum(rnorm(nrow(df))) 

p = ggplot(df) + 
    geom_line(aes(Date, value), size=0.1) + 
    scale_y_continuous(name= "Title of y [units]")+ 
    scale_x_date(breaks=pretty_breaks(), date_minor_breaks="1 month") + 
    theme_bw() 
p 

enter image description here

enter image description here

在这里,我改变了date_minor_breaks="6 months"避免多余的个月 enter image description here

尼斯和简单!

+0

感谢Marco。这对我目前的任务来说并不是非常有用,但是在将来我想我会回头看看你的帖子。你的情节看起来不错,我不得不看看秤包。 –