Home > Software engineering >  How to add a minor grid in boxplots in ggplot2?
How to add a minor grid in boxplots in ggplot2?

Time:06-26

I want to add a vertical minor grid between two major grids in a boxplot with discrete x variables in ggplot2.

This is the sample:

boxplot <- ggplot(data = mtcars ,aes(x = as.factor(cyl),y=wt, fill=as.factor(am)))   geom_boxplot()
boxplot

As seen from the visualization, it can be unclear which box belongs to which x label because the major vertical grid is separating the two boxes at the same x-variable (it may not be an issue here, but it does become problematic when there are many x variables and narrow boxes). Therefore, I am thinking of adding a minor grid in the middle of each major grid. I tried using the "minor grid.x" in ggplot2, shown below, but I could not see any added lines.

boxplot   theme(panel.grid.minor.x = element_line(color="black"))

I've looked over related posts on setting gridlines, but it seems that they are focused on continuous x variables, and is not applicable to box plots.

Thank you in advance.

CodePudding user response:

Update thanks to @Allan Cameron:

ggplot(data = mtcars ,aes(x =factor(cyl),y=wt, fill=as.factor(am)))   
  geom_boxplot()  
  geom_vline(xintercept = c(1.5, 2.5),linetype="dashed",colour="green",size=1)

First answer:

Are you looking for such a solution:

library(ggplot2)
ggplot(data = mtcars ,aes(x =factor(cyl),y=wt, fill=as.factor(am)))   
  geom_boxplot()  
  geom_vline(aes(xintercept=1.5),linetype="dashed",colour="green",size=1) 
  geom_vline(aes(xintercept=2.5),linetype="dashed",colour="green",size=1)

enter image description here

CodePudding user response:

You can try this and modify the values of the theme and see what works better for you:

boxplot   
  theme(
    panel.grid.major.y = element_line(color = "blue",
                                      size = 0.5,
                                      linetype = 2),
    panel.grid.minor.y = element_line(color = "red",
                                        size = 0.25,
                                        linetype = 1),
    panel.grid.major.x = element_line(color = "green",
                                      size = 0.5,
                                      linetype = 3)
    )

enter image description here

  • Related