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

寻求基于ggplot2的向日葵图(sunflower plot)实现方案

在ggplot2中实现向日葵图

需求说明

需要在ggplot2中制作向日葵图,将重叠数据点以“花瓣”形式展示——每片花瓣对应一个重叠的数据点,替代geom_count用点大小表示计数的方式,实现类似基础包sunflowerplot()的效果,且能与其他ggplot2图层无缝集成。

实现思路

核心是围绕重叠坐标点生成均匀分布的线段模拟花瓣,步骤如下:

  • 统计每个(x,y)坐标组合的观测次数
  • 对每个坐标点,根据观测数生成对应数量的均匀角度(0到2π区间内)
  • 设定花瓣长度,计算每个花瓣的终点坐标
  • 用线段绘制花瓣,搭配中心点完成向日葵效果

代码实现

library(tidyverse)

# 示例数据
tb <- tibble::tibble(
  x = c(rep(0, 5), rep(1, 1), rep(0, 3), rep(1, 2)),
  y = c(rep(0, 5), rep(1, 1), rep(1, 3), rep(0, 2))
)

# 预处理生成花瓣坐标
sunflower_data <- tb %>%
  # 统计每个(x,y)的观测数量
  count(x, y, name = "n") %>%
  # 为每个点生成对应数量的均匀分布角度
  mutate(angle = map(n, ~seq(0, 2*pi, length.out = .x + 1)[-.x - 1])) %>%
  unnest(angle) %>%
  # 设定花瓣长度(可根据需求调整)
  mutate(petal_length = 0.1,
         x_end = x + petal_length * cos(angle),
         y_end = y + petal_length * sin(angle))

# 绘制向日葵图
ggplot() +
  # 绘制花瓣线段
  geom_segment(data = sunflower_data,
               aes(x = x, y = y, xend = x_end, yend = y_end),
               linewidth = 1) +
  # 绘制每个点的中心原点
  geom_point(data = sunflower_data %>% distinct(x, y, n),
             aes(x = x, y = y),
             size = 3, color = "black") +
  # 匹配基础sunflowerplot的坐标轴显示
  scale_x_continuous(breaks = c(0, 1)) +
  scale_y_continuous(breaks = c(0, 1)) +
  theme_minimal()

自定义说明

  • 调整petal_length参数可控制花瓣长短,适配不同绘图场景
  • 若需区分分组,可在geom_segment的aes中添加color或linetype映射
  • 该方案基于ggplot2原生函数实现,无需额外扩展包,可直接与geom_text(标注计数)、geom_smooth(添加拟合线)等图层结合使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:25:07