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

如何在ggplot中绘制已知中心点、尺寸及旋转角度的矩形

实现方法

实现思路

ggplot原生的geom_rect不支持基于中心点的旋转配置,因此我们可以先通过几何运算计算每个矩形旋转后的四个顶点坐标,再使用geom_polygon绘制即可。

完整实现代码

library(tidyverse)

# 原始数据集
tbl <- tibble(center_x = c(10, 50),
              center_y = c(20, 30),
              width = c(4, 7),
              length = c(8, 12),
              angle = c(120, 45), # 角度单位为度
              color = c("blue", "yellow"))

# 计算每个矩形四个顶点的坐标
point_tbl <- tbl %>%
  mutate(rect_id = row_number(), # 给每个矩形分配唯一ID,避免后续绘图混淆
         theta = pi * angle / 180) %>% # 角度转弧度适配R的三角函数计算
  uncount(4, .id = "point_id") %>% # 每个矩形扩展为4行,对应4个顶点
  # 计算未旋转时顶点相对中心点的偏移量
  mutate(
    x_rel = case_when(
      point_id == 1 ~ length/2,
      point_id == 2 ~ -length/2,
      point_id == 3 ~ -length/2,
      point_id == 4 ~ length/2
    ),
    y_rel = case_when(
      point_id == 1 ~ width/2,
      point_id == 2 ~ width/2,
      point_id == 3 ~ -width/2,
      point_id == 4 ~ -width/2
    )
  ) %>%
  # 应用旋转矩阵计算旋转后的偏移量
  mutate(
    x_rot = x_rel * cos(theta) - y_rel * sin(theta),
    y_rot = x_rel * sin(theta) + y_rel * cos(theta)
  ) %>%
  # 叠加中心点坐标得到顶点的绝对位置
  mutate(
    x_abs = center_x + x_rot,
    y_abs = center_y + y_rot
  )

# 绘图
ggplot(point_tbl, aes(x = x_abs, y = y_abs)) +
  geom_polygon(aes(group = rect_id, fill = color), alpha = 0.8, color = "black", linewidth = 0.5) +
  scale_fill_identity() + # 直接使用数据中定义的颜色作为填充色
  coord_equal() + # 保持坐标轴比例一致,避免矩形显示变形
  theme_bw()

补充说明

  • 如果你不需要使用数据中定义的color列作为填充色,删除scale_fill_identity()即可,ggplot会自动分配默认配色
  • 若需要调整矩形边框粗细、透明度,直接修改geom_polygon的linewidth、alpha参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:54:06