2014-09-30 35 views
0

这是我目前epicurve:X轴的主要和次要刻度日期标签和休息(epicurve)

enter image description here

和代码来生成它:

# generate random sample of dates and sex 
df = data.frame(dates = Sys.Date() + sample(-10:25, 100, replace = T), 
      sex = sample(c("M", "F"), 25, replace = T)) 

require(ggplot2); require(scales) 

# set x-axis limits 
xlmts = c(Sys.Date() - 22, Sys.Date() + 30) 

p = ggplot(df, aes(x = dates, fill = sex)) 

p = p + geom_bar(stat = "bin", colour = "black") 

p = p + scale_x_date(breaks = "1 day", labels=date_format("%a \n %d \n %m"), 
       limits = xlmts) 

p 

这大致我希望我的epicruve的样子:

enter image description here

我有两个问题,我的x轴:

第1期 - 休息

  1. 尽管我设置“scale_x_date”多天已经组合在一起
  2. “打破=1天”

第2期 - 主要和次要刻度标记

2.1有没有什么办法让缩写日期名在90 DEGR ee角度,并保持天数和月数在0度。

2.2有没有什么方法可以显示一个月的数字(最好在月中居中),这样它就不会像上面的例子那样在每个主要的刻度标签上重复。

回答

2

这会让你更进一步(我没有添加线条),但它非常体力劳动。

在主要剧情,我:

  • 使用随机种子,使其可重复:-)
  • 预先计算的M/F每天
  • 旋转X轴标签计数(只用一天短名称)
  • 展开情节利润率容纳额外的X轴注释

然后我:

  • 产生,并通过annotation_custom
  • 添加非旋转,在月日#的产生,并通过annotation_custom
  • 添加非旋转月份数字建立最终的情节电网结构
  • 关闭该面板夹RECT
  • 绘制图形与grid.draw

你prbly想间距a位打。

这应该足以让你去(并且添加行应该是lineGrob非常适合)。

library(dplyr) 
library(ggplot2) 
library(scales) 
library(grid) 
library(gridExtra) 

set.seed(1492) # reproducible 

df = data.frame(dates = Sys.Date() + sample(-10:25, 100, replace = T), 
       sex = sample(c("M", "F"), 25, replace = T)) 

# pre-compute the M/F counts per date 

df.2 <- df %>% group_by(dates, sex) %>% summarise(count=n()) 

gg <- ggplot(df.2, aes(x=dates, y=count, fill=sex)) 
gg <- gg + geom_bar(color="black", position="stack", stat="identity") 
gg <- gg + scale_x_date(breaks="1 day", 
         labels=date_format("%a"), 
         limits = xlmts) 
gg <- gg + labs(x=NULL) 
gg <- gg + theme_bw() 
gg <- gg + theme(axis.text.x=element_text(angle = 90, hjust = 1)) 
gg <- gg + theme(plot.margin=unit(c(1,1,5,1), "line")) 

gg1 <- gg # keep base plot 

# make & plot the day #'s 

for (d in seq(from=as.Date("2014-09-06"), to=as.Date("2014-11-01"), by="1 day")) { 
    d1 <- format(as.Date(d, origin="1970-01-01"), "%d") 
    gg1 <- gg1 + annotation_custom(grob=textGrob(d1, hjust=0, gp=gpar(cex=0.7)), ymin=-0.8, ymax=-0.8, 
           xmin=as.numeric(d), xmax=as.numeric(d)) 
} 

# add month numbners 

gg1 <- gg1 + annotation_custom(grob=textGrob("9", gp=gpar(cex=0.8)), ymin=-1.0, ymax=-1.0, 
          xmin=as.numeric(as.Date("2014-09-17")), xmax=as.numeric(as.Date("2014-09-17"))) 
gg1 <- gg1 + annotation_custom(grob=textGrob("10", gp=gpar(cex=0.8)), ymin=-1.0, ymax=-1.0, 
          xmin=as.numeric(as.Date("2014-10-12")), xmax=as.numeric(as.Date("2014-10-12"))) 

# build the plot 

gg2 <- ggplot_gtable(ggplot_build(gg1)) 

# no panel clipping 
gg2$layout$clip[gg2$layout$name=="panel"] <- "off" 

# draw the plot 

grid.draw(gg2) 

enter image description here

+0

哎呀。看起来我并没有为这一年做一个'annotation_custom',但是基于示例中的其他位很容易添加 – hrbrmstr 2014-09-30 13:35:58

相关问题