我有一个时间序列,我正在检查数据异质性,并希望向一些数据分析师解释其中的一些重要方面。我有一个由 KDE 图覆盖的密度直方图(为了清楚地看到两个图)。然而,原始数据是计数,我想将计数值作为直方图条上方的标签放置。
这是一些代码:
$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
同时,在这个直方图上添加一条密度曲线,
您可能会使用 geom_histogram()
首先记录binwidth
值(value)! (这个很重要!),接下来添加一层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);
关于R:ggplot2:使用密度叠加向直方图添加计数标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11404531/