You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言基础绘图:箱线图上移及X轴标签添加(非ggplot2)

Hey there! Let's work through your base R boxplot problems one by one—no ggplot2 needed, just good old base R tricks.

1. Shift the boxplot upward to make space for long X-axis labels

The key here is adjusting the plot margins or drawing area to free up space at the bottom. Here are two reliable methods:

Method 1: Adjust plot margins with par(mar)

The mar parameter controls margin size (in lines of text) for the bottom, left, top, and right sides (in that order). Increasing the bottom margin will automatically push the boxplot upward:

# Set margins: bottom=8 lines, left=4, top=2, right=2 (adjust numbers to fit your label length)
par(mar = c(8, 4, 2, 2))

# Draw your boxplot (example using mtcars dataset)
boxplot(mpg ~ cyl, data = mtcars, ylab = "Miles per Gallon")

Method 2: Fine-tune the plot area with par(plt)

For more precise control, use plt to define the plot area as a fraction of the device (values from 0 to 1). Increasing the bottom value shifts the entire plot upward:

# plt = c(left, right, bottom, top)
par(plt = c(0.1, 0.9, 0.2, 0.9))  # Reserves 20% of the bottom space, moving the plot up

# Draw your boxplot
boxplot(mpg ~ cyl, data = mtcars)

2. Fix the disappearing X-axis label from mtext()

The "flash and disappear" issue usually stems from one of two things:

  • Calling mtext() after closing the plot device (like dev.off()), or
  • The label being cut off because it’s too close to the axis (wrong line parameter).

Here’s the correct workflow to add a persistent X-axis label:

# First set your margins (as above)
par(mar = c(8, 4, 2, 2))

# Draw the boxplot (hide default X-axis with xaxt="n" if you want custom tick labels)
boxplot(mpg ~ cyl, data = mtcars, xaxt = "n", ylab = "Miles per Gallon")

# Optional: Add custom X-axis ticks/labels (wrap long text with \n to break lines)
axis(1, at = 1:3, labels = c("4 Cylinders\n(High Efficiency)", "6 Cylinders\n(Balanced)", "8 Cylinders\n(High Power)"), line = 1)

# Add the X-axis title with mtext()—use line=N to push it down far enough to avoid cutting
mtext("Engine Cylinder Count (Detailed Category Description)", side = 1, line = 4, cex = 0.8)

# Alternatively, use title() which is often more intuitive:
# title(xlab = "Engine Cylinder Count (Detailed Category Description)", line = 4)

Pro tip: Always run mtext() or title() right after drawing the boxplot, before closing the plot device. If you’re in RStudio, make sure the plot pane is active so the label renders properly.

内容的提问来源于stack exchange,提问作者BelleT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:27:44