如何告诉R的ggplot2为某些x轴值设置刻度线,并保持其他值的垂直线

amh*_*amh 7 r ggplot2

我正在使用R中的ggplot2创建一个时间序列.我想知道如何在标记的月份(例如Mar 07,Mar 08等)中显示x轴上的刻度线,同时保持垂直灰线为每个月.

主要原因是因为每个月都有一个刻度标记,因此很难知道哪一个与标签相对应.

这是一个情节的例子:

看看x轴上的刻度如何让人们很难知道每个月的位置

这是后面的R线:

ggplot(timeseries_plot_data_mean,aes(as.numeric(project_date)))+
   geom_line(aes(y=num_views))+geom_point(aes(y=num_views))+
   stat_smooth(aes(y=num_views),method="lm")+
   scale_x_continuous(breaks = xscale$breaks, labels = xscale$labels)+
   opts(title="Monthly average num views")+xlab("months")+ylab("num views")
Run Code Online (Sandbox Code Playgroud)

这是想要产生的.查看刻度线如何定位在月份标签的正上方,垂直线仍然显示每个月.

这就是想要生成的东西(Inkscape,图像编辑器,奇怪地取代了q的点

我使用Inkscape手动编辑上面的图,(忽略q,Inkscape奇怪地取代了q的点)

bde*_*est 9

这是一个使用minor_breaks参数的解决方案scale_x_date().要使用它,您的x值必须是class Date而不是numeric.

library(ggplot2)
set.seed(123)

x <- seq(as.Date("2007/3/1"), as.Date("2012/4/1"), by = "1 month")
y <- ((exp(-10 * seq(from=0, to=1, length.out=length(x))) * 120) +
      runif(length(x), min=-10, max=10))

dat <- data.frame(Months=x, Views=y)

x_breaks <- seq(as.Date("2007/3/1"), as.Date("2012/4/1"), by="1 year")
x_labels <- as.character(x_breaks, format="%h-%y")

plot_1 <- ggplot(dat, aes(x=Months, y=Views)) +
          theme_bw() +
          geom_line() +
          geom_point() +
          scale_x_date(breaks=x_breaks, labels=x_labels, minor_breaks=dat$Months)

png("plot_1.png", width=600, height=240)
print(plot_1)
dev.off()
Run Code Online (Sandbox Code Playgroud)

plot_1.png