【问题标题】:Showing X axis value label on top of the histogram在直方图顶部显示 X 轴值标签
【发布时间】:2018-03-12 17:44:54
【问题描述】:

我搜索了这个,但我只提出了这个类似的问题,但在堆叠直方图中标记了计数值。我想要做的是在每个直方图条的顶部标记一个 price 值。

使用类似的histogram-ggplot-show-count-label-for-each-bin-for-each-category

  ggplot(aes(x = price ), data = diamonds) + 
  geom_histogram(aes(fill = cut ), binwidth=1500, colour="grey20", lwd=0.2) +
  stat_bin(binwidth=1500, geom="text", colour="white", size=3.5,
           aes(label=..count.., group=cut, y=0.8*(..count..))) +
  scale_x_continuous(breaks=seq(0,max(diamonds$price), 1500))

当我将 label=..count.. 更改为 ..price.. 时,我得到了

FUN(X[[i]], ...) 中的错误:找不到对象“价格”

我们如何将price 值放在每个直方图的顶部?

提前致谢!

【问题讨论】:

  • This 线程似乎有你的答案。回复:您的错误,..count.. 是一个特定的内置 stat 变量,它调用类似于 sum 的东西
  • 您将如何决定为垃圾箱显示哪个奇异价格值?这些垃圾箱包含一系列价格。
  • @MrFlick 说得好。中间值就好了!

标签: r ggplot2


【解决方案1】:

这是一种拼凑而成的。我不知道如何为平均值或中位数等函数重新定义类似 ..count.. 的特殊变量。相反,我计算了每个箱内的平均价格,然后计算annotate-d。我选择不将平均价格放在条形顶部,因为这会错误地向读者暗示这些是计数值,但事实并非如此。

library(plyr)
mean.cut <- ddply(diamonds, .(cut(price,seq(0,max(diamonds$price), 1500))), 
                              summarize, v=mean(price))

ggplot(diamonds) +geom_histogram(aes(x=price,fill = cut ), binwidth=1500, 
                                 colour="grey20", lwd=0.2) +  
  scale_x_continuous(breaks=seq(0,max(diamonds$price), 1500))+
  annotate("text", x=seq(0,max(diamonds$price), 1500),  y=mean.cut$v,
                  label=round(mean.cut$v,0))

我玩弄了 hte 价格值的格式,并喜欢我尝试过的各种选项标签的这段代码:

label=sprintf(" $%-5s", round(mean.cut$v,-1) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多