本文介绍了带有与x轴对齐的小节内部注释的geom_bar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用geom_bar创建结果的直方图,并且希望将结果数作为文本包含在与x轴对齐的每个栏中。



这是我到目前为止:

  df< -  data.frame(results = rnorm(100000))

require(ggplot2)

p = ggplot(df,aes(x = results))

p = p + geom_bar(binwidth = 0.5,color =black,fill =white,drop = T)

p = p + scale_y_log10()

p = p + geom_hline(aes(yintercept = 1))

p = p + stat_bin(geom =text,binwidth = 0.5,
aes(x = results,angle = 90,y = 2,
label = gsub(,,格式(.. count ..,big.mark =,,
scientific = F))))

p


您可以看到文本与x轴不一致,而且我的真实数据更大(在数以百万计)这个问题会变得更糟:

当前数字:

所需数字:
解决方案你可以通过交换 geom stat 来实现。换句话说,使用 geom_text(stat =bin,...)



这允许您明确设置 y 位置(即在 aes 之外),并指定与 hjust = 0 $ b

试试这个:

  ggplot(df, aes(x = results))+ 
geom_bar(binwidth = 0.5,color =black,fill =white,drop = T)+
scale_y_log10()+
geom_hline(aes (yintercept = 1))+
geom_text(stat =bin,binwidth = 0.5,y = 0.1,hjust = 0,
aes(x = results,angle = 90,
label = gsub(,,格式(.. count ..,big.mark =,,
scientific = F))))

I'm trying to create a histogram of results using geom_bar and want to include the count of results as text within each bar aligned with the x-axis.

This is what i have so far:

df <- data.frame(results = rnorm(100000))

require(ggplot2)

p = ggplot(df, aes(x =  results)) 

p = p + geom_bar(binwidth = 0.5, colour = "black", fill = "white", drop = T)

p = p + scale_y_log10()

p = p + geom_hline(aes(yintercept = 1))

p = p + stat_bin(geom = "text", binwidth = 0.5,
             aes(x = results, angle = 90, y = 2, 
                 label = gsub(" ", "",format(..count.., big.mark = ",", 
                                             scientific=F)))) 

p

As you can see the text is not aligned with the x-axis and as my true data is far larger (in the order of millions) this problem is made slightly worse:

Current figure:

Desired figure:

Note: by setting y = 3 in stat_bin i get a warning stating "Mapping a variable to y and also using stat="bin". etc..." but am not sure how to force the position of the text to be at the bottom of the graph without defining a y value.

解决方案

You can do this by swapping the geom and the stat. In other words, use geom_text(stat="bin", ...).

This allows you to explicitly set the y position (i.e. outside the aes) and also specify the text alignment with hjust=0.

Try this:

ggplot(df, aes(x =  results)) +
  geom_bar(binwidth = 0.5, colour = "black", fill = "white", drop = T) +
  scale_y_log10() +
  geom_hline(aes(yintercept = 1)) +
  geom_text(stat="bin", binwidth = 0.5, y=0.1, hjust=0,
           aes(x = results, angle = 90, 
               label = gsub(" ", "", format(..count.., big.mark = ",", 
                                            scientific=F)))) 

这篇关于带有与x轴对齐的小节内部注释的geom_bar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 09:38