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

如何使用ggplot2的coord_polar绘制嵌套同心圆

解决方法

核心调整是在coord_polar中指定x轴值映射为角度,同时关闭x轴范围扩展保证线条首尾闭合,具体实现代码如下:

library(ggplot2)
library(tidyverse)

# 构造原始数据
x1 <- seq(0, 6000000, 1000)
y1 <- rep(1, length(x1))
y2 <- rep(2, length(x1))
data <- as.data.frame(cbind(x1, y1, y2))

# 转换为长数据格式,方便统一映射
data_long <- data %>% 
  pivot_longer(cols = c(y1, y2), names_to = "circle", values_to = "radius")

绘图代码:

ggplot(data_long, aes(x = x1, y = radius, group = circle)) +
  geom_line(linewidth = 1) +
  # 指定x轴映射为极坐标的角度,关闭x轴扩展保证首尾闭合为完整圆形
  coord_polar(theta = "x", expand = FALSE) +
  # 调整y轴范围,隐藏y轴刻度标签
  scale_y_continuous(limits = c(0, 3), breaks = NULL, labels = NULL) +
  # 清理多余的主题元素
  theme_minimal() +
  theme(
    axis.title = element_blank(),
    panel.grid = element_blank(),
    legend.position = "none"
  )

说明

  • y值对应同心圆的半径,修改y1/y2的取值即可调整两个圆的相对大小
  • x值与极坐标角度一一对应,后续需要在圆上标注x轴相关差异时,直接按x的取值添加标注元素即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:36:05