【问题标题】:R: ggplot2: Adding count labels to histogram with density overlayR:ggplot2:将计数标签添加到具有密度叠加的直方图
【发布时间】:2012-07-09 23:10:43
【问题描述】:

我正在检查数据异构性的时间序列,并希望向一些数据分析师解释其中的一些重要方面。我有一个由 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() 函数还不是很了解,但是任何想法都会有所帮助。非常感谢!

【问题讨论】:

    标签: r ggplot2 label histogram


    【解决方案1】:

    如果想让y轴显示bin_count的数字,同时在这个直方图上加一条密度曲线,

    您可以先使用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);
    

    【讨论】:

      猜你喜欢
      • 2015-11-08
      • 2020-08-08
      • 2018-12-05
      • 2020-06-01
      • 2021-03-14
      相关资源
      最近更新 更多