Remove one tick on the x axis in ggplot2 in R?

I make a bargraph in ggplot2, and to explain the reasons I need spaces between some of my bars. I use the limits in scale_x_discrete to insert empty bars, which gives me the gap I need.

The gap between groups b and c in my layout data looks perfect, but the gap between a and b still has a black mark and a white line in the background. I don't need any x-axis grid lines, so I can solve the white line problem quite easily, but I cannot decide how to get rid of the label.

I am using R version 3.3.1 (2016-06-21) - "Error in your hair" while working in RStudio, and this code requires ggplot2

 ### Mock data with the same structure as mine my.data <- data.frame(x = rep(c("a", "b", "c", "d"), 3), y = c("e", "f", "g")) ### Make graph ggplot(my.data, aes(x = x, fill = y)) + geom_bar(position = "fill") + scale_x_discrete(limits = c("a", "", "b", "", "c", "d")) ### Remove white line in background by removing all x grid lines ggplot (my.data, aes(x = x, fill = y)) + geom_bar(position = "fill") + scale_x_discrete(limits = c("a", "", "b", "", "c", "d")) + theme(panel.grid.minor.x = element_blank(), panel.grid.major.x = element_blank()) 

How to remove a black mark between a and b ?

If I need to change the way I insert spaces between columns, how can I do this and maintain the chart structure?

Image showing white x-axis line and black tick mark

+6
source share
1 answer

You can do what you ask by hacking: if you replace the empty limits with the first value "a" , ggplot will place the bar in the first occurrence and leave the following empty:

 my.data <-data.frame (x=rep(c("a", "b", "c", "d"),3), y=c("e", "f", "g")) ggplot(my.data, aes(x=x, fill = y)) + geom_bar(position = "fill") + scale_x_discrete(limits = c("a", "a", "b", "a", "c", "d")) 

hacked plot

However, the correct way to separate variables is with a facet, which requires the variable to define the groups you want, for example.

 library(dplyr) # create with your favorite grammar my.data %>% mutate(grp = case_when(.$x == 'a' ~ 1, .$x == 'b' ~ 2, TRUE ~ 3)) #> xy grp #> 1 ae 1 #> 2 bf 2 #> 3 cg 3 #> 4 de 3 #> 5 af 1 #> 6 bg 2 #> 7 ce 3 #> 8 df 3 #> 9 ag 1 #> 10 be 2 #> 11 cf 3 #> 12 dg 3 

which you can pass ggplot to facet:

 my.data %>% mutate(grp = case_when(.$x == 'a' ~ 1, .$x == 'b' ~ 2, TRUE ~ 3)) %>% ggplot(aes(x, fill = y)) + geom_bar(position = 'fill') + facet_grid(. ~ grp, space = 'free_x', scales = 'free_x') 

facetted plot

+6
source

All Articles