当使用离散值时,ggplot2在值的中心处的刻度值处提供网格线
library(reshape2)
ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) +
geom_bar(stat="identity", position=position_dodge())
如何设置x轴的网格线以显示在离散值之间(即'Dinner'和'Lunch'之间)
我试图设置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())
答案 0 :(得分:6)
您可以添加一条垂直线作为网格线,如下所示:
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")
答案 1 :(得分:1)
遇到了同样的问题。我的解决方案是使网格线更大..
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, color=sex)) +
geom_point(stat="identity", position=position_dodge()) +
theme(panel.grid.major.x = element_line(color = "white", size = 20))