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

如何使Calendar Heatmap色块贴合分面网格线且保持标签居中?

Fix: Align geom_tile with Facet Grid Lines (Keep Axis Labels Centered)

I’ve struggled with this exact calendar heatmap issue in ggplot2 before—discrete axis scales cause annoying gaps between tiles, and trying to fix it with axis() never quite works right. Here’s a clean solution that adjusts your tile positioning and axis setup to get perfect alignment while keeping labels centered:

Full Working Code

library(ggplot2)
library(plyr)
library(scales)
library(zoo)

# Data prep (mostly your original code)
df <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/yahoo.csv")
df$date <- as.Date(df$date)
df <- df[df$year >= 2012, ]

# Calculate week of month (keep as numeric for continuous scaling)
df$yearmonth <- as.yearmon(df$date)
df$yearmonthf <- factor(df$yearmonth)
df <- ddply(df, .(yearmonthf), transform, 
            monthweek = 1 + week - min(week))

# Build the adjusted heatmap
ggplot(df, aes(x = monthweek, y = weekdayf, fill = VIX.Close)) + 
  # Tiles that fill entire grid cells
  geom_tile(colour = "white", width = 1, height = 1) + 
  facet_grid(year ~ monthf) + 
  scale_fill_gradient(low = "red", high = "green") +
  # Ensure x-axis labels stay centered on tiles
  scale_x_continuous(
    breaks = unique(df$monthweek),
    labels = unique(df$monthweek),
    expand = c(0, 0)  # Remove padding to align tiles with facet edges
  ) +
  theme(
    panel.grid = element_blank(),  # No need for grid lines—tiles fill the space
    panel.spacing = unit(0, "lines")  # Optional: tighten gap between facets
  ) +
  labs(x = "Week of Month", y = "", 
       title = "Time-Series Calendar Heatmap", 
       subtitle = "Yahoo Closing Price", fill = "Close")

What Changed & Why

  • Continuous X-Axis Instead of Discrete: By leaving monthweek as a numeric value (not converting to factor), we can control tile placement precisely, avoiding gaps that come with discrete scales.
  • geom_tile(width = 1, height = 1): This forces each tile to exactly match the size of one grid cell, eliminating gaps between tiles and making them align perfectly with facet lines.
  • scale_x_continuous(expand = c(0,0)): Removes the default padding around the plot, so the first and last tiles touch the edges of the facet panels.
  • Centered Labels: Using breaks = unique(df$monthweek) places each x-axis label directly at the midpoint of its corresponding tile, since monthweek represents the center of each grid cell.

This method avoids the clunky workarounds with axis() and gives you a clean, tight heatmap where tiles fit perfectly within the facet grid.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:30:35