Home > Back-end >  How can I center the bar graphs in a facet wrap and remove the x axis labels in the facets?
How can I center the bar graphs in a facet wrap and remove the x axis labels in the facets?

Time:01-06

I am seeking help with ggplot facetwraps to generate a figure where the bars are centered within each facet, and there are no labels on the x-axis on the facets (since they are labeled above).

How would you go about achieving this?

First, generate the data frame

act <- c("Wildlife viewing", "Wildlife viewing", "Wildlife viewing", 
         "Birdwatching", "Birdwatching", "Birdwatching", 
         "Wildlife photography", "Wildlife photography", "Wildlife photography", 
         "Deer hunting", "Deer hunting", "Deer hunting", 
         "Trapping", "Trapping", "Trapping", 
         "Fishing", "Fishing", "Fishing")

ppart <- c(65.87091, 60.64611, 66.12500,
           37.66578, 35.97651, 41.75000,
           29.00088, 26.28488, 30.50000, 
           53.40407, 28.92805, 42.37500, 
           9.018568, 3.524229, 5.250000, 
           63.21839, 44.19971, 57.62500)

Region <- c("UP", "SL", "NL", 
            "UP", "SL", "NL", 
            "UP", "SL", "NL",
            "UP", "SL", "NL",
            "UP", "SL", "NL",
            "UP", "SL", "NL")

df <- data.frame(act, ppart, Region) # create a df with % participation in various activities

Then, create the graphic.

ggplot(df, aes(x = act, y = ppart, fill = Region))   
    geom_bar(position = "dodge", stat = "identity")   
    facet_wrap(~act)  
  scale_fill_grey(start = 0.8, end = 0.2)  
    ylab("Percent participation in activity")   
  xlab("")   
    theme_bw()

Resulting figure

As you can see, when I use the above code to generate the graph, things are a bit smushed and there are obvious issues with spacing and labels. How can I resolve these?

Specifically, centering the bar graphs within each facet and removing the x-axis labels within facets. Please advise! Thank you.

CodePudding user response:

I think the canonical method is to use scales = "free_x" in the facet, and to explicit remove the x-axis ticks with breaks=NULL.

ggplot(df, aes(x = act, y = ppart, fill = Region))   
    geom_bar(position = "dodge", stat = "identity")   
    facet_wrap(~act, scales = "free_x")     # changed
  scale_fill_grey(start = 0.8, end = 0.2)  
    ylab("Percent participation in activity")   
  xlab("")   
    theme_bw()  
  scale_x_discrete(breaks = NULL)           # new

enter image description here

CodePudding user response:

Is this what you are after?

ggplot(df, aes(x = 0, y = ppart, fill = Region))   
  geom_bar(position = "dodge", stat = "identity")   
  facet_wrap(~act)  
  scale_fill_grey(start = 0.8, end = 0.2)  
  ylab("Percent participation in activity")   
  xlab("")   
  theme_bw()  
  theme(
    axis.text.x = element_blank()
  )

enter image description here

  •  Tags:  
  • Related