使用ggplot2绘制环形密度图

4

我正在处理循环数据,并希望使用ggplot2重现这种类型的图表:

library(circular)

data1 <- rvonmises(1000, circular(0), 10, control.circular=list(units="radians")) ##        sample
quantile.circular(data1,c(0.05,.95)) ## for interval

data2 <- mean(data1)
dens <- density(data1, bw=27)
p<-plot(dens, points.plot=TRUE, xlim=c(-1,2.1),ylim=c(-1.0,1.2),
main="Circular Density", ylab="", xlab="")
points(circular(0), plot.info=p, col="blue",type="o")
arrows.circular(c(5.7683795,0.5151433    )) ## confidence interval
arrows.circular(data2, lwd=3) ## circular mean
  1. 最细的箭头是我的区间的极端值
  2. 我假设蓝点是预测
  3. 第三个箭头是圆形平均值
  4. 我需要圆形密度

我一直在寻找类似的东西,但没有找到任何东西。 有什么建议吗?

谢谢


查看?coord_polar。我不熟悉circular数据格式,但你可能可以得到一些有效的结果。 - Gregor Thomas
你说得对,谢谢。 - Uzg
您也可以在不使用极坐标的情况下强制数据的循环性。(ggplot示例)(基本R示例)。 - filups21
1个回答

2
为了避免走错方向,请您快速检查一下这段代码是否朝着正确的方向前进?使用+arrow(...)并适当加载即可轻松添加箭头。
编辑:有一个关于附加密度值的复杂方法的备注 - ggplot的geom_density似乎不喜欢coord_polar(至少我尝试过的方式)。
#create some dummy radial data and wrap it in a dataframe
d1<-runif(100,min=0,max=120)
df = NULL
df$d1 <- d1
df <- as.data.frame(df)

#estimate kernel density and then derive an approximate function to attach density values to the radial values in the dataframe
data_density <- density(d1)
density_function <- with(data_density, approxfun(x, y, rule=1))
df$density <- density_function(df$d1)

#order dataframe to facilitate geom_line in polar coordinates
df <- df[order(df$density,df$d1),]

#ggplot object
require(ggplot2)
g = ggplot(df,aes(x=d1,y=density))
#Radial observations on unit circle
g = g + geom_point(aes(x=d1,y=min(df$density)))
#Density function
g = g + geom_line()
g = g + ylim(0,max(df$density))
g = g + xlim(0,360)
#polar coordinates
g = g + coord_polar()
g

从(0,120)中采样的均匀随机变量:

enter image description here


另一个问题,我可以将coord_polar设置为弧度吗? - Uzg
从文档来看,geom_coord实际上需要弧度制。在我的代码中,你可以创建一个随机变量在[0,pi]范围内,然后设置xlim(0,2*pi)来说明这一点。我个人一直很难理解弧度和极坐标,但是coord_polar对输入非常宽容 :) - CMichael
1
关于 stat_density 的问题,ggplot 的极坐标实现实际上只是标准笛卡尔图的一个变换。没有任何 stat_* 知道你的数据是圆形的。你仍然可以绘制大多数内容,但需要先进行任何计算,并显式地将坐标传递给 ggplot 进行绘制。 - Gregor Thomas
谢谢你的澄清,Gregor! - CMichael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接