2014-06-07 81 views
1

之间的网格线在使用GGPLOT2处的值GGPLOT2:离散值

library(reshape2) 

ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) + 
    geom_bar(stat="identity", position=position_dodge()) 

enter image description here

如何设置网格线从所述x的中心提供在刻度值的网格线的离散值轴之间出现离散值(即'晚餐'和'午餐'之间)

然而,我试图设置panel.grid.minor.x然而(我认为),因为它是离散的这不起作用...这不是一个小值因为它在上面绘制了边线。

ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) + 
    geom_bar(stat="identity", position=position_dodge()) + 
    theme(panel.grid.minor.x = element_line()) 

回答

4

您可以添加一条垂直线,将如下充当网格线:可以,当然,改变线宽,颜色,样式等,根据需要

geom_vline(xintercept=1.5, colour='white') 

你,和如果您有几组需要由网格线分隔的小节,则在适当的位置添加多行。例如,使用一些假的数据:

set.seed(1) 
dat = data.frame(total_bill=rnorm(100,80,10), 
       sex=rep(c("Male","Female"),50), 
       time=sample(c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"), 
          100, replace=TRUE)) 
dat$time = factor(dat$time, 
        levels=c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"), 
        ordered=TRUE) 

ggplot(data=dat, aes(x=time, y=total_bill, fill=sex)) + 
    geom_bar(stat="identity", position=position_dodge()) + 
    geom_vline(xintercept=seq(1.5, length(unique(dat$time))-0.5, 1), 
      lwd=1, colour="black") 

enter image description here

+0

谢谢您的回答。我实际上在'scales ='free_x''上使用'facet_grid',所以像这样使用'length'是有问题的。我已经看了一下,但无法找到如何获得每个方面的滴答数。 –

+0

如果您的免费比例是数字或有序因子,则可以使用'max(dat $ var_name)'而不是'length(unique(dat $ var_name))'。这有帮助,还是你的情况比这更复杂? – eipi10