如何避免ggplot2绘制水平条形图时轴文本被部分截断?
I totally get the frustration when your carefully crafted axis labels get cut off—let's fix that right away. Here are a few proven solutions tailored to your code:
Solution 1: Adjust Plot Margins
The most common fix is adding extra space to the margin where the truncated text sits. Since you used coord_flip(), your original x-axis labels (quality levels) are now on the vertical axis (y-axis after flipping). We can add left margin space to accommodate them:
df = data.frame(quality = c("low", "medium", "high", "perfect"), n = c(0.1, 11, 0.32, 87.45)) require(ggplot2) require(dplyr) size = 20 df %>% ggplot() + geom_bar(aes(x = quality, y = n), stat = "identity", fill = "gray70", position = "dodge") + geom_text(aes(x = quality, y = n, label = paste0(round(n, 2), "%")), position = position_dodge(width = 0.9), hjust = -0.2, size = 10, color = "gray50") + coord_flip() + ggtitle("Quality Distribution") # Added a sample title since yours was truncated theme( plot.margin = margin(10, 10, 10, 50), # Top, Right, Bottom, Left margins (in points) axis.text.y = element_text(hjust = 1) # Align text to the right to fit in the new margin )
Tweak the left margin value (the last number in margin()) if your labels are still getting cut off—increase it until everything fits.
Solution 2: Adjust Axis Text Alignment and Internal Margin
If your labels are large or tightly packed, adding space directly around the axis text can help:
theme( axis.text.y = element_text( size = 12, # Reduce size if needed hjust = 1, margin = margin(r = 10) # Add right margin to the text itself ) )
This creates a buffer between the axis text and the axis line, preventing overlap or truncation.
Solution 3: Extend Axis Range with expand_limits
Sometimes the plot area is too tight around the axis. Extending the y-axis (original x-axis) range can create extra breathing room:
df %>% ggplot() + # ... your existing plot layers ... expand_limits(y = c(-5, 100)) # Adjust values based on your data's range
This adds empty space on either end of the axis, giving labels room to display fully.
Bonus: Wrap Long Labels with str_wrap
If you have longer quality labels down the line, wrapping them into multiple lines can prevent truncation without sacrificing readability:
# First install/load stringr if you haven't already # install.packages("stringr") library(stringr) df$quality = str_wrap(df$quality, width = 5) # Wrap labels at 5 characters
Start with adjusting the plot margins—it’s usually the quickest and most effective fix for this issue!
内容的提问来源于stack exchange,提问作者Seymour




