ggplot facet_grid条形图:调整条形宽度、间距及面板尺寸
Hey there! I totally get your frustration with those wonky bar and panel spacings—let's work through this together to get your plot looking clean and polished. Here are targeted fixes for each of your pain points:
1. Narrow the Gap Between Bar Groups
The main issue with your wide spacing after setting width=0.3 is how position_dodge2() handles padding around groups. Instead of switching back to position_dodge(), tweak the padding argument in position_dodge2() to shrink the space between your bar groups:
geom_barh(stat="identity", aes(fill=methode), position=position_dodge2(width=0.3, padding=0.05), # Lower padding = tighter groups width = 0.3)
widthmatches your bar width to keep bars slimpaddingcontrols the empty space between differentFraktiongroups—start with 0.05 and adjust up/down until it looks right
2. Fix Y-Axis Expansion Without Extra White Space
Instead of using scale_y_discrete(expand = c(0, 2)) (which adds huge top/bottom padding), use the expansion() function for precise control:
scale_y_discrete(expand = expansion(add = c(0.2, 0.2))) # Smaller add values = less empty space
This reduces the gap between Fraktion labels while keeping the plot tightly cropped at the top and bottom.
3. Adjust Spacing Between facet_grid Panels
plot.margin affects the entire plot's outer edges, not the space between facets. Use panel.spacing.x (since your facets are horizontal) to tweak the gap between Standort panels:
theme( axis.text.x = element_text(hjust = 1), legend.title=element_blank(), panel.spacing.x = unit(0.8, "cm") # Adjust this value to widen/narrow panel gaps )
Full Modified Code
Putting it all together, here's your updated code with all fixes applied:
plot1 <- ggplot(data2, aes(x=fc4mean, y=Fraktion, fill=methode)) + facet_grid(~Standort, scales="free_y") + geom_barh(stat="identity", position=position_dodge2(width=0.3, padding=0.05), width = 0.3) + theme_bw() + theme( axis.text.x = element_text(hjust = 1), legend.title=element_blank(), panel.spacing.x = unit(0.8, "cm") # Adjust panel gap here ) + scale_fill_brewer(palette = "Greys", direction=-1) + scale_color_brewer(palette="Black") + # Fixed typo here (added palette=) ylab("fraction") + guides(colour = guide_legend(reverse=T)) + geom_errorbar(aes(xmin=fc4mean-fc4sd, xmax=fc4mean+fc4sd), position=position_dodge2(width=0.3, padding=0.05), # Match dodge settings to bars width=0.3) + scale_y_discrete(expand = expansion(add = c(0.2, 0.2))) # Tighten y-axis padding
Note: I fixed a small typo in scale_color_brewer() by adding palette="Black" to make it valid.
Bonus Tip
If you still see minor clipping of elements (like error bars or labels), add coord_cartesian(clip = "off") to the end of your plot code—it lets elements extend slightly beyond the plot panel without getting cut off.
内容的提问来源于stack exchange,提问作者Hans Schmidt

