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

R语言绘图问题:如何在每个矩形内部绘制圆形 现有代码绘制的圆形超出范围

示例图

问题原因

原有代码生成的圆默认以坐标原点(0,0)为圆心、半径为1,而你绘制的矩形x坐标范围是1~2,自然会落在矩形外部。同时原有矩形生成逻辑会得到8个高度逐层递减的叠放矩形,也不符合每个矩形单独放圆的需求。

修改后代码

plot.new()
plot.window(xlim = c(-1,9), ylim = c(-1,9), asp = 1)

# 绘制8个竖排独立矩形,每个宽1、高1
rect_left <- 1
rect_right <- 2
rect_ybottom <- 1:8
rect_ytop <- rect_ybottom + 1
rect(rect_left, rect_ybottom, rect_right, rect_ytop)

# 生成半径为0.5的基础圆坐标(适配矩形宽高的最大内切圆)
theta <- seq(0, 2 * pi, length = 72)
base_circle_x <- 0.5 * cos(theta)
base_circle_y <- 0.5 * sin(theta)

# 遍历每个矩形,在中心位置绘制圆
for (i in seq_along(rect_ybottom)) {
  center_x <- (rect_left + rect_right) / 2
  center_y <- (rect_ybottom[i] + rect_ytop[i]) / 2
  # 平移基础圆到当前矩形中心
  polygon(base_circle_x + center_x, base_circle_y + center_y)
}

补充说明

如果需要生成横排的矩形,只需修改矩形参数即可:

# 横排8个矩形示例
rect_left <- 1:8
rect_right <- rect_left + 1
rect_ybottom <- 1
rect_ytop <- 2
rect(rect_left, rect_ybottom, rect_right, rect_ytop)

# 对应圆形绘制逻辑调整x坐标即可
for (i in seq_along(rect_left)) {
  center_x <- (rect_left[i] + rect_right[i]) / 2
  center_y <- (rect_ybottom + rect_ytop) / 2
  polygon(base_circle_x + center_x, base_circle_y + center_y)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:18:04