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

使用geom_contour_filled()遇breaks相关错误,求解决方法

问题修复方案

错误根源

你遇到的错误是因为在geom_contour_filled()中同时指定了bins和breaks参数——这两个参数互斥,只能二选一:

  • bins用于自动指定等高线的分箱数量
  • breaks用于手动定义等高线的断点值

除此之外,代码还有两处需要调整的细节:

  1. geom_contour_filled()生成的是离散填充区间,无法搭配连续型的scale_fill_gradient()比例尺
  2. 插值后的变量命名错误(NMDS1/NMDS2应该对应原始的tau/time)

修正后的完整代码

# Function to read and process a single CSV file
process_csv <- function(file_name, time_stamp) {
  # Read the CSV file, skipping the first three rows
  df <- read_csv(file_name, skip = 3)
  
  # Use the CSV name as a time stamp
  df$time <- time_stamp
  
  # Convert tau to log10 scale
  df$tau <- log10(df$tau)
  
  return(df)
}

# List of CSV files (assuming they are in your working directory)
filelist_grad = list.files(pattern = "*.csv")
csv_files <- stringr::str_sort(filelist_grad, numeric = TRUE)

# Time stamps based on CSV file names
time_stamps <- seq(0.5, by = 0.5, length.out = length(csv_files))

# Process each CSV file and combine them into a single data frame
data_list <- mapply(process_csv, csv_files, time_stamps, SIMPLIFY = FALSE)
combined_df <- bind_rows(data_list)

# Interpolate data to a regular grid
d1 <- with(combined_df, interp(x = tau, y = time, z = gamma))

# Melt the z matrix to long format
d2 <- melt(d1$z, na.rm = TRUE)
names(d2) <- c("x", "y", "gamma")

# 修正变量命名:对应原始的tau和time
d2$tau <- d1$x[d2$x]
d2$time <- d1$y[d2$y]

# Create the plot
ggplot(data = d2, aes(x = tau, y = time, z = gamma)) +
  # 移除bins参数,保留手动指定的breaks
  geom_contour_filled(breaks = seq(0, 120, by = 10)) +
  # 用scale_fill_steps匹配离散填充区间,保留黄红渐变需求
  scale_fill_steps(low = "yellow", high = "red", limits = c(0, 100)) +
  theme_minimal()

关键修改说明

  1. 移除bins参数:保留breaks=seq(0,120,by=10)手动控制等高线断点,解决参数冲突问题
  2. 替换填充比例尺:scale_fill_steps()专门适配离散区间的渐变填充,和geom_contour_filled()的输出匹配
  3. 修正变量命名:将插值后的x/y轴变量改回tau/time,和原始数据逻辑一致,避免混淆
  4. 移除多余group参数:geom_contour_filled()会自动根据z值分组绘制等高线,无需手动指定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:48:27