Thi*_*dge 3 label r ggplot2 geom-text
我遇到了使用 ggplot2 错误排序数据标签的问题。
不幸的是,关于这个主题的其他 SE Q&A 并不是很有见地(示例),所以我不得不与 reprex 联系。我有以下数据:
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))))
Run Code Online (Sandbox Code Playgroud)
如果我然后尝试使用此代码绘制此数据:
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)
Run Code Online (Sandbox Code Playgroud)
我得到这个不正确的标签顺序:
我已经使用了年龄变量的排序(例如 rev(capacity)),但我无法解决这个问题。任何人都可以为整个 SE 社区提供关于如何处理标签订购的更全面的答案吗?
您需要调用position参数 ingeom_text以匹配填充的美学数据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)
Run Code Online (Sandbox Code Playgroud)