Tusuubira Edward
Tusuubira Edward

Reputation: 1

How do I plot facet wrap of varying x width of discrete variable while ensuring the column width is the same throughout

I Am looking for 2 things to achieve a good presentation of my data.

  1. Create face wrap of varying with to achieve constant col width throughout.
  2. Suitable reorder of stacked cols according to height for easy visual comparison

enter image description here

Below is my code

RI_pH<-data.frame(RI_pH)
RI_pH$Landcover<-factor(RI_pH$Landcover,levels =c("Bare","Vegetation","Mixed"))
RI_pH$Predictor<-factor(RI_pH$Predictor,levels=c("Landsat8","Landsat8 & Sentinel1",
                                              "Sentinel1","All Variables"))

bar<-ggplot(RI_pH,aes(x=Variable,y=RI,fill=Landcover))+
geom_col(width =0.5)+
facet_wrap(~Predictor,scales = "free")+
scale_x_discrete()+
theme(axis.text.x = element_text(angle = 90,  hjust=0.95,vjust=0.2, size=32))+
 theme(axis.text.y=element_text(size=32))+
theme(strip.text = element text(size=52, face=2))

jpeg(file="bar%03d.jpeg",width=1180,height=849,
  pointsize=52,bg="white",units="mm",res=95)
plot(bar)
dev.off()

Upvotes: 0

Views: 686

Answers (1)

Jon Spring
Jon Spring

Reputation: 66425

The only guaranteed automatic way to get constant column widths with varying facet widths would be to have a single row using facet_grid(scales = "free_x", space = "free_x"), since there are configurations of data where that would be impossible to accommodate within the built-in constraints of ggplot2 (e.g. facet widths must align from one row to the next).

library(ggplot2)
ggplot(mtcars, aes(as.factor(gear), wt, fill = as.factor(cyl))) +
  geom_col() +
  facet_grid(~carb, scales = "free_x", space = "free_x")

enter image description here

If you want a more customized layout, you might need to lean on packages like patchwork to help you combine plots, but I can't think of a straightforward way to keep the column widths aligned between rows.

library(patchwork)
a <- ggplot(subset(mtcars, carb <=3), 
       aes(as.factor(gear), wt, fill = as.factor(am))) +
  geom_col() +
  facet_grid(~carb, scales = "free_x", space = "free_x") 
b <- ggplot(subset(mtcars, carb > 3),
       aes(as.factor(gear), wt, fill = as.factor(am))) +
  geom_col() +
  facet_grid(~carb, scales = "free_x", space = "free_x")
(a / b) + plot_layout(guides = "collect")

enter image description here

Upvotes: 1

Related Questions