2017-10-17 147 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。這對我目前的任務來說並不是非常有用,但是在將來我想我會回頭看看你的帖子。你的情節看起來不錯,我不得不看看秤包。 –