使用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
相关产品推荐
相关产品推荐

