Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot2中的密度直方图:标签栏高度_R_Ggplot2_Histogram - Fatal编程技术网

R ggplot2中的密度直方图:标签栏高度

R ggplot2中的密度直方图:标签栏高度,r,ggplot2,histogram,R,Ggplot2,Histogram,我有数据告诉我解决一项任务需要多少分钟: dat = data.frame(a = c(5.5,7,4,20,4.75,6,5,8.5,10,10.5,13.5,14,11)) 我用ggplot2软件包绘制了数据的密度直方图: p=ggplot(dat, aes(x=a)) + geom_histogram(aes(y=..density..),breaks = seq(4,20,by=2))+xlab("Required Solving Time") 现在我想在上面添加每个密度条高度的标签

我有数据告诉我解决一项任务需要多少分钟:

dat = data.frame(a = c(5.5,7,4,20,4.75,6,5,8.5,10,10.5,13.5,14,11))
我用ggplot2软件包绘制了数据的密度直方图:

p=ggplot(dat, aes(x=a)) + geom_histogram(aes(y=..density..),breaks = seq(4,20,by=2))+xlab("Required Solving Time")
现在我想在上面添加每个密度条高度的标签。我试着找到这个 通过添加
+geom_文本(标签=…密度…)
。 这将返回错误

找不到对象“…密度…”

不过。有人知道
geom_text()
函数的输入是什么吗 以我的情况得到那些标签

没有
geom_text()
的解决方案也不错,但我更喜欢
您可以使用
ggplot\u build()


您可以使用
stat\u-bin
geom=“text”
标记这些条
stat_bin
计算计数,我们使用
.density..
将其转换为密度,就像
geom_直方图
一样。但通过设置
geom=“text”
,我们将这些密度值显示为文本。我们还需要为
geom_直方图
stat_bin
设置相同的
中断
,以便密度值匹配。我已经在标签的中间放置了文本标签,在标签中乘以<代码>…密度>代码> 0.5。不过,你当然可以随意调整

breaks = seq(4,20,by=2)  

ggplot(dat, aes(x=a)) + 
  geom_histogram(aes(y=..density..), breaks = breaks) + 
  stat_bin(geom="text", aes(label=round(..density..,2), y=0.5*..density..), 
           breaks=breaks, colour="white") +
  xlab("Required Solving Time")

要获取位于条上方的标签,可以使用:

ggplot(dat, aes(x=a)) + 
  geom_histogram(aes(y=..density..), breaks = breaks) + 
  stat_bin(geom="text", aes(label=round(..density..,2), y=..density..),
           breaks=breaks, vjust = -1) +
  xlab("Required Solving Time")

。密度..
来自统计数据,因此您需要告诉该层也使用装箱统计数据

p + geom_text(aes(label=round(..density.., 2), y=..density..), 
              stat="bin", breaks = seq(4,20,by=2), 
              col="white", vjust=1)

这就是你想要的吗?是的,我在搜索stackoverflow时看到了这个答案,但在我的例子中,它是一个密度直方图,而不是绝对频率条。我无法从这个答案中得出问题的解决方案……在对Hadley的评论中,“强烈建议[s]不要”使用PANEL之类的内部变量,我将其视为ggplot_build()输出中的一列。ggpplot_build()中的其他变量(如密度)是否被认为使用更安全?或者ggplot_build(p)$data$面板不是“内部”面板,可以安全使用?似乎表明ggplot_build()应该像任何东西一样可靠,因为它是由print.ggplot返回的(不可见)。哈德利的警告是从2013年开始的。。。
p + geom_text(aes(label=round(..density.., 2), y=..density..), 
              stat="bin", breaks = seq(4,20,by=2), 
              col="white", vjust=1)