离散值之间的网格线 [英] Gridlines between discrete values

查看:47
本文介绍了离散值之间的网格线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用离散值时,ggplot2在刻度值的中间提供一条网格线

When using a discrete values ggplot2 provides a gridline at the tick value at the centre of the value

library(reshape2)

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

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

How can I set the grid line from the x axis to appear between the discrete values (i.e. between 'Dinner' and 'Lunch')

我试图设置 panel.grid.minor.x ,但是(我认为)因为它是离散的,所以不起作用...这对于绘制网格线不是一个小值上.

I have tried to set panel.grid.minor.x however (I think) as it is discrete this does not work ... this is not a minor value for it to plot the girdline on.

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())

推荐答案

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

You can add a vertical line that will act as a grid line as follows:

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

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

You can, of course, alter line width, colour, style, etc. as needed, and add multiple lines in the appropriate locations if you have several groups of bars that need to be separated by grid lines. For example, using some fake data:

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")

这篇关于离散值之间的网格线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆