ggplot2:离散值之间的网格线

Chr*_*ett 6 r ggplot2

当使用离散值时,ggplot2在值的中心处的刻度值处提供网格线

library(reshape2)

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

在此输入图像描述

如何从x轴设置网格线以显示在离散值之间(即"晚餐"和"午餐"之间)

我试图设置panel.grid.minor.x(我认为),因为它是离散的,这不起作用...这不是一个小的值来绘制girdline.

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())
Run Code Online (Sandbox Code Playgroud)

eip*_*i10 7

您可以添加一条垂直线作为网格线,如下所示:

geom_vline(xintercept=1.5, colour='white')
Run Code Online (Sandbox Code Playgroud)

当然,您可以根据需要更改线宽,颜色,样式等,如果有多组需要用网格线分隔的条形,则可以在适当的位置添加多条线.例如,使用一些假数据:

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述