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

使用coord_polar()和geom_histogram()绘制0-360度极坐标直方图的问题

极坐标直方图0度区间缺失/0与360度重复刻度问题

我想创建可环绕的极坐标直方图,但代码无法显示0度区间的数据。查阅coord_polar()文档未找到解决方法,推测问题出在geom_histogram()上。

初始代码及问题

angles   <- data.frame(x = rnorm(10000, mean = 270, sd = 75))
angles$x <- angles$x %% 360

ggplot(angles, aes(x = x)) +
  geom_histogram(binwidth = 15, colour = "black", size = .25) +
  scale_x_continuous(limits = c(0, 360),
                      breaks = seq(0, 360, by = 30),
                    minor_breaks = seq(0, 360, by = 15))  +
  # scale_y_continuous(limits = c(0, 500)) +
  coord_polar(start = 0) +
  theme(plot.title = element_text(hjust = 0.5)) + 
  labs(y = 'Count', x = '')

运行后可见0/360度没有对应的区间。

编辑后的尝试及新问题

移除scale_x_continuous()中的limits参数后,图表可环绕,但0和360度变为独立刻度。

angles <- data.frame(x = runif(10000, 0, 360))
angles$x  <- angles$x %% 360

ggplot(angles, aes(x = x)) +
  geom_histogram(binwidth = 15, colour = "black", size = .25) +
  scale_x_continuous(breaks = seq(0, 360, by = 30),
                     minor_breaks = seq(0, 360, by = 15))  +
  # scale_y_continuous(limits = c(0, 500)) +
  coord_polar(start = 0, clip = "off") +
  theme(plot.title = element_text(hjust = 0.5)) + 
  labs(y = 'Count', x = '')

解决方案

方法一:手动分箱合并0/360区间

通过手动分箱将345-360度的数据合并到0-15度区间,同时调整刻度避免重复:

library(ggplot2)

angles <- data.frame(x = rnorm(10000, mean = 270, sd = 75))
angles$x <- angles$x %% 360

# 按15度分箱,将345-360度的箱标签替换为0
angles$bin <- cut(angles$x, breaks = seq(0, 360, 15), include.lowest = TRUE, labels = seq(0, 345, 15))
angles$bin[angles$bin == "345"] <- "0"
angles$bin <- as.numeric(as.character(angles$bin))

ggplot(angles, aes(x = bin)) +
  geom_bar(colour = "black", size = .25) +
  scale_x_continuous(breaks = seq(0, 330, 30),
                     minor_breaks = seq(0, 345, 15)) +
  coord_polar(start = 0) +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(y = 'Count', x = '')

方法二:利用boundary参数校准分箱

指定geom_histogram的boundary = 0确保分箱从0开始,同时调整刻度只显示到330度:

library(ggplot2)

angles <- data.frame(x = rnorm(10000, mean = 270, sd = 75))
angles$x <- angles$x %% 360

ggplot(angles, aes(x = x)) +
  geom_histogram(binwidth = 15, colour = "black", size = .25, boundary = 0) +
  scale_x_continuous(breaks = seq(0, 330, 30),
                     minor_breaks = seq(0, 345, 15),
                     limits = c(0, 360)) +
  coord_polar(start = 0, clip = "off") +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(y = 'Count', x = '')

两种方法都能实现0度区间正常显示且图表环绕,同时避免0和360度刻度重复。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 11:13:15