r - ggplot2 以错误的顺序放置数据标签(geom_text)

我遇到了使用 ggplot2 错误排序数据标签的问题。

不幸的是,关于这个主题的其他 SE 问答不是很有见地(example),所以我不得不与代表联系。我有以下数据:

df = as.data.frame(structure(list(geotype = c('urban','urban','urban','urban','suburban','suburban','suburban','suburban'),
                              limitations = c('all','some','all','some','all','some','all','some'),
                              metric = c('lte','lte','5g','5g','lte','lte','5g','5g'),
                              capacity=c(12,11,5,4,14,10,5,3))))

如果我然后尝试使用此代码绘制此数据:

ggplot(df, aes(x = geotype, y = capacity, fill=metric)) + geom_bar(stat="identity") + 
 facet_grid(~limitations) +  
 geom_text(data = df, aes(geotype, capacity + 2, label=capacity), size = 3) 

我的标签顺序不正确:

我已经尝试了很长时间的变量排序(例如 rev(capacity)),但我无法解决这个问题。关于如何处理标签排序,谁能为整个 SE 社区提供更全面的答案?

最佳答案

您需要调用 geom_text 中的 position 参数来匹配填充的美学数据与 geom_bar 并让函数知道数据是堆叠。

ggplot(df, aes(x = geotype, y = capacity, fill=metric)) + 
  geom_bar(stat="identity") + 
  geom_text(data = df, aes(geotype, capacity, label=capacity), size = 3, vjust = 2,
           position = position_stack()) +
  facet_grid(~limitations)

https://stackoverflow.com/questions/52870049/

相关文章:

authentication - Kubernetes 基于 LDAP 的用户身份验证

powershell - 在 Powershell 中实现装饰器模式

perl - Docker [for mac] 文件系统变为只读,这几乎破坏了 docker 的所有

abap - 没有 BY 的 SORT 在标准内部表上的行为?安全吗?

sas - 对SAS中的动态列数进行排名

jsf-2 - ResponseWriter.writeAttribute() 中 'name' 和

react-native - 如何在不影响内部 View 元素的情况下应用阴影来 react 原生

assembly - ARM v8 中的 LDUR 和 STUR

apache - 使用 ApacheDS 创建新的架构 LDAP

vuejs2 - 如何在 v-radio 标签中设置 HTML