且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

geom_text不标记躲避的geom_bar

更新时间:2023-01-28 12:50:38

您需要更新 geom_text 以使用 position_dodge()函数.这是一个使用内置菱形数据集的示例,与您的示例非常相似.我还使用了 ggplot 3.0的 stat()函数,而不是已弃用的 .count .. 变量.

You need to update geom_text to use the position_dodge() function. Here's an example, very similar to yours, using the built-in diamonds data set. I'm also using ggplot 3.0's stat() function, rather than the deprecated ..count.. variable.

您的标签显示在最右边,因为它们代表每个组的总数计数,因此位于相应的较高y位置.

Your labels appear far to the right because they represent the total count for each of your groups, and are thus placed at the corresponding higher (farther right) y position.

请注意,提供 position_dodge()的宽度值为0.9对应于以下事实:默认情况下,分类条形图(或一组躲避的条形图)占用了其90%的可用空间.轴,其余的10%会移至条形分组之间的边距.

Note that providing position_dodge() a width value of 0.9 corresponds to the fact that by default, a categorical bar (or a dodged group of bars) takes up 90% of its available space on the axis, with the remaining 10% going to the margin between the bar groupings.

g <- ggplot(data = diamonds, aes(x = cut, fill = color)) +
  geom_bar(position = 'dodge') +
  geom_text(stat = 'count', hjust = 0, position = position_dodge(0.9), aes(x = cut, label = stat(count))) +
  coord_flip()
print(g)