2012-07-09 105 views
4

我有一个时间序列,我正在检查数据异质性,并希望向某些数据分析师解释一些重要方面。我有一个由KDE图覆盖的密度直方图(以便明显地看到两个图)。但是原始数据是计数,我想将计数值作为标签放在直方图条上方。R:ggplot2:将计数标签添加到密度叠加的直方图

下面是一些代码:

$tix_hist <- ggplot(tix, aes(x=Tix_Cnt)) 
      + geom_histogram(aes(y = ..density..), colour="black", fill="orange", binwidth=50) 
      + xlab("Bin") + ylab("Density") + geom_density(aes(y = ..density..),fill=NA, colour="blue") 
      + scale_x_continuous(breaks=seq(1,1700,by=100)) 

    tix_hist + opts(
     title = "Ticket Density To-Date", 
     plot.title = theme_text(face="bold", size=18), 
     axis.title.x = theme_text(face="bold", size=16), 
     axis.title.y = theme_text(face="bold", size=14, angle=90), 
     axis.text.x = theme_text(face="bold", size=14), 
     axis.text.y = theme_text(face="bold", size=14) 
      ) 

我想过使用外推KDE带宽等计数值。是否可以将ggplot频率直方图的数字输出框架化并将其添加为“图层”。我还不清楚layer()函数,但任何想法都会有所帮助。非常感谢!

如果你想y轴,以显示 bin_count号,在同一时间,在这个柱状图添加密度曲线

回答

2

您可以使用geom_histogram()第一和记录binwidth价值! (这非常重要!),接下来添加一层geom_density()以显示拟合曲线。

,如果你不知道如何选择binwidth值,你可以计算出:

my_binwidth = (max(Tix_Cnt)-min(Tix_Cnt))/30; 

(这正是geom_histogram确实在默认情况下)。

的代码如下:

(假设你刚刚计算出的binwith值为0.001)

tix_hist <- ggplot(tix, aes(x=Tix_Cnt)) ; 

tix_hist<- tix_hist + geom_histogram(aes(y=..count..),colour="blue",fill="white",binwidth=0.001); 

tix_hist<- tix_hist + geom_density(aes(y=0.001*..count..),alpha=0.2,fill="#FF6666",adjust=4); 

print(tix_hist);