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

R语言箱线图问题:为Y轴添加刻度并显示含均值的箱线

Fixing Your R Boxplot Issues: Y-Axis Ticks & Mean Values

Hey there! Let’s get your boxplot working exactly how you want it—there are two main tweaks needed, starting with fixing your data format (the root cause of most of your issues) and then adding the mean values and proper Y-axis ticks.

Step 1: Fix the Data Format

Looking at your data, the DFT values use commas as decimal separators (like 1,61), but R defaults to recognizing periods as decimals. That means your DFT column was being read as text instead of numbers, which breaks the boxplot and Y-axis scaling entirely.

Fix this either when reading the data:

DFTvalues <- read.table(file.choose(), header = TRUE, dec = ",")

Or if you’ve already loaded the data, convert the column manually:

DFTvalues$DFT <- as.numeric(gsub(",", ".", DFTvalues$DFT))

Step 2: Update Your ggplot Code

Now that your data is properly formatted as numerical values, let’s adjust the code to add mean markers and clear Y-axis ticks:

library(ggplot2)

# Base plot setup
p <- ggplot(data = DFTvalues, aes(x = Quarter, y = DFT))

# Build the final plot with all desired elements
q <- p +
  geom_jitter(aes(color = Quarter), width = 0.2) +  # Adjust width to stop point overlap
  geom_boxplot(alpha = 0.7, outlier.color = NA) +
  # Add a distinct mean point (white-filled diamond for easy visibility)
  stat_summary(fun = mean, geom = "point", shape = 23, fill = "white", size = 3) +
  # Set custom Y-axis ticks (tweak the sequence to match your full data range)
  scale_y_continuous(breaks = seq(1.5, 2.7, 0.1))

# Display the plot
q

Quick Breakdown of Key Changes:

  • dec = ",": Tells R to interpret commas as decimal points during data import, ensuring DFT is treated as a numerical column.
  • stat_summary(fun = mean): Adds a clear marker for the mean of each quarter’s DFT values—this stands out against the boxplot’s median line.
  • scale_y_continuous(breaks = ...): Manually sets Y-axis ticks at 0.1 intervals (you can adjust seq(1.5, 2.7, 0.1) to start/end at different values or use a larger/smaller step if your full dataset needs it).
  • width = 0.2 in geom_jitter: Spreads out the jittered points so they don’t cluster too tightly and obscure each other.

Run this code, and your plot should match your expected output with proper Y-axis scaling, visible ticks, and mean values clearly marked!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:53:35