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

如何在R语言ggplot2热图中绘制连贯的日出/日落连线?

热图中日出/日落连贯连线实现方案

问题描述

我有一张展示每日各时段特定信息的热图,同时拥有时间轴内每日的日出、日落时段数据。目前我仅能绘制出日出和日落的「短线条」,请问能否将这些短线条分别连成连贯的日出连线与日落连线?

原代码:

heatmap_plot <- df %>%
  ggplot(aes(x = Hour, y = interaction_order, fill = presence)) +
  geom_tile(size = 0.5) +
  scale_fill_gradientn(colors = custom_palette, na.value = "grey") +
  theme_minimal() +
  labs(x = "Hour", y = "Day") +
  theme(legend.position = "none",
        panel.grid = element_blank(),
        axis.text.y = element_text(size = 0)) +
  scale_x_continuous(breaks = unique(df$Hour)) +
  geom_line(data = line_data, aes(x = Sunrise_hour, y = interaction_order),linetype = "solid", color = "black", size = 1) +
  geom_line(data = line_data, aes(x = Sunset_hour, y = interaction_order), linetype = "solid", color = "black", size = 1) +
  geom_point(data = line_data, aes(x = Sunrise_hour, y = interaction_order), color = "black", size = 1) +
  geom_point(data = line_data, aes(x = Sunset_hour, y = interaction_order), color = "black", size = 1)
print(heatmap_plot)

解决方案

问题出在geom_line的分组逻辑:默认情况下ggplot会按数据行分组,而你的line_data每行对应一天的日出/日落数据,单组只有一个点,所以只能画出单个点的"短线条"。只需给geom_line添加group = 1参数,让所有日出点归为同一组、所有日落点归为同一组,就能实现连贯连线。

修改后的完整代码

# 确保line_data按日期顺序排序(interaction_order升序)
line_data <- line_data %>% arrange(interaction_order)

heatmap_plot <- df %>%
  ggplot(aes(x = Hour, y = interaction_order, fill = presence)) +
  geom_tile(size = 0.5) +
  scale_fill_gradientn(colors = custom_palette, na.value = "grey") +
  theme_minimal() +
  labs(x = "Hour", y = "Day") +
  theme(legend.position = "none",
        panel.grid = element_blank(),
        axis.text.y = element_text(size = 0)) +
  scale_x_continuous(breaks = unique(df$Hour)) +
  # 日出连线:指定group=1
  geom_line(data = line_data, aes(x = Sunrise_hour, y = interaction_order, group = 1), 
            linetype = "solid", color = "black", size = 1) +
  # 日落连线:指定group=1
  geom_line(data = line_data, aes(x = Sunset_hour, y = interaction_order, group = 1), 
            linetype = "solid", color = "black", size = 1) +
  geom_point(data = line_data, aes(x = Sunrise_hour, y = interaction_order), color = "black", size = 1) +
  geom_point(data = line_data, aes(x = Sunset_hour, y = interaction_order), color = "black", size = 1)
print(heatmap_plot)

关键说明

  • group = 1:强制把所有行的日出点(或日落点)视为同一组,ggplot会按interaction_order的顺序连接这些点。
  • 提前排序line_data:确保日期是按时间顺序排列的,避免连线出现交叉或混乱。

内容的提问来源于stack exchange,提问作者Inês

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:40:15