R:ggplot2:使用密度叠加向直方图添加计数标签

标签 r ggplot2 label histogram

我有一个时间序列,我正在检查数据异质性,并希望向一些数据分析师解释其中的一些重要方面。我有一个由 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/

相关文章:

r - 使用 "shinyjs"包控制 Shiny 仪表板菜单项的可见/不可见

r - 使用 ggplot2 在 R 上创建地平线图 : show percentage change

r - ggplot coord_polar() 在 pi/2 和 -pi/2 之间绘制顶部和底部

swift - 您需要帮助在连接到步进器的标签中存储数字

ios - swift - 在 Controller 之间切换后更新计时器并更新标签

r - 我们能否整齐地将回归方程与R2和p值对齐?

r - 分隔符为空格且缺失值为空时如何读取?

windows - 如何使用 R 检查字符串是否是 Windows 的有效文件名?

R:圣诞树

r - 手动为ggplot2中的长X标签创建缩写图例