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

ggplot中geom_tile在x轴为非字符类型时首尾多出冗余列的问题求助

解决ggplot热力图时间步出现额外列的问题

问题根源

你的Timestep是整数类型,ggplot会将其当作连续型变量处理,自动扩展坐标轴范围以覆盖“合理”的连续区间,这就是为什么会出现数据中不存在的t=0和t=32列。

最优解决方案

把Timestep转换成有序因子(ordered factor)——既保留时间步的自然顺序,又让ggplot将其当作离散型变量,只显示数据中存在的时间点,不会额外生成无关列。

代码修改点

在函数的类型处理部分,替换为以下代码:

# 将Timestep转为有序因子,指定水平为实际存在的时间步顺序
df$Timestep <- factor(df$Timestep, levels = as.character(1:ncol(dataToDraw)), ordered = TRUE)
df$value <- as.integer(df$value)  # 保留原有的数值类型转换

方案优势

  • 避免了普通字符类型的排序问题:普通字符会按字典序排列(比如"10"会排在"2"前面),而有序因子可以手动指定1、2、3...的正确顺序。
  • 不需要给时间步加前缀,轴标签保持干净的数字格式,同时彻底解决了额外列的问题。

完整修改后的函数

drawHeatmap <- function(dataToDraw, solutionToHighlight, plotTitle) {
  rownames(dataToDraw) <- as.character(c("Scheduler", 4:1))

  colnames(dataToDraw) <- c(1:ncol(dataToDraw))
  df <- melt(dataToDraw)
  colnames(df) <- c("Process","Timestep","value")
  
  # 修改Timestep为有序因子
  df$Timestep <- factor(df$Timestep, levels = as.character(1:ncol(dataToDraw)), ordered = TRUE)
  df$value <- as.integer(df$value)  # Convert in order to use continuous scale
  
  solution_path <- highlightCorrectPath(t(solutionToHighlight))
 
  ggplot() +
    coord_fixed() +
    scale_fill_gradientn(name = "Occurences", colors = c("blue", "green", "yellow", "orange", "red")) +
    geom_tile(data = df, aes(x=Timestep, y=Process, fill = value)) +
    scale_color_manual(values=c("black"), labels = c("Solution cells")) + 
    geom_rect(aes(xmin = solution_path[,"x_left"],
                  xmax = solution_path[,"x_right"],
                  ymin =  solution_path[,"y_bottom"],
                  ymax =  solution_path[,"y_top"], color = "Solution Cells"),
              fill=NA, size=1.1) +
    labs(title=plotTitle) +
    theme(legend.position = "bottom")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:05:25