简体   繁体   English

使用ggplot2在x轴上的月份之间添加刻度

[英]Adding ticks between months on x-axis using ggplot2

I'm trying to add ticks between the months on the x-axis using ggplot2 - something like this: 我正在尝试使用ggplot2在x轴的月份之间添加刻度线-像这样:

在此处输入图片说明

instead of the standard ticks at the months. 而不是标准的蜱几个月。

My process thus far has been as follows (for example): 到目前为止,我的流程如下(例如):

y=(1:1:12)
x=seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by="months")
df=data.frame(x,y)
g<-ggplot(df,aes(x,y))
g<-g+geom_line()
g<-g+scale_x_date(labels = date_format("%b-%y"),breaks = date_breaks("months"))

Which gives me: 这给了我:

在此处输入图片说明

I'd like those x-axis ticks to be between the months. 我希望这些X轴刻度在两个月之间。 I've tried using 我试过使用

 minor_breaks=date_breaks("2 weeks")

in the scale_x_date line (along with several other variations), but the minor_breaks doesn't seem to be working for me. 在scale_x_date行中(以及其他几种变体),但是minor_breaks似乎对我不起作用。 I've also tried variations of 我也尝试过

 myminor=seq(from=1,to=365,by=15)

and using that for minor_breaks, but that didn't work either. 并将其用于minor_breaks,但这也不起作用。 Finally, I tried 最后,我尝试了

g<-g+theme(axis.ticks.x=element_line(myminor))

but that also proved ineffective. 但这也被证明是无效的。 I feel like it's a simple fix but I'm stuck. 我觉得这是一个简单的解决方法,但我遇到了麻烦。

Fairly hacky, but somewhat closer to what you seem to want: 相当hacky,但有点接近您想要的东西:

library(ggplot2)
library(scales)
library(lubridate)
y=(1:12)
x=seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by="months")
df=data.frame(x,y)
g<-ggplot(df,aes(x,y))
g<-g+geom_line()

labels <- date_format("%b")(x)
breaks <- as.Date(sort(c(as.POSIXct(x), 
                         as.POSIXct(seq(as.Date("2014-01-15"), 
                                        as.Date("2014-12-31"), by="months")),
                         ymd("2015-1-1"))))
labels <- c("", 
            as.vector(rbind(labels, 
                            rep("", length(labels)))))

g + scale_x_date(labels = labels, breaks = breaks, limits=range(breaks)) + 
    theme(axis.ticks.x=element_line(colour=c("black", 
                                             rep(c(NA, "black"), t=12))),
          panel.grid.major.x=element_line(colour=c("white", 
                                                   rep(c(NA, "white"), t=12))),
          panel.grid.minor.x=element_blank())

Imgur

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM