ggplot2将数据标签(geom_text)放在错误的顺序中

3

我在使用ggplot2时,数据标签的顺序错误。

不幸的是,在这个话题上其他SE Q&A(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) 

我得到了这个不正确的标签顺序:

enter image description here

我已经尝试了很久变量的排序(例如,rev(capacity)),但是我无法解决这个问题。有没有人能够为整个SE社区提供更全面的答案来处理标签的排序?

3个回答

6

您需要在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)

enter image description here


1

您可以在邮件 ggplot 的 aes 中设置标签

ggplot(df, aes(x = geotype, y = capacity, fill = metric, label = capacity ) ) + 
  geom_col() + 
  geom_text( size = 3, position = position_stack( vjust = 0.5 ) ) +
  facet_grid( ~limitations )

enter image description here


0

像这样吗?位置堆栈。

g <- ggplot(df, aes(x = geotype, y = capacity, fill = metric, label = 
capacity))
g + geom_col() + facet_grid(~limitations) +
geom_text(size = 3, vjust =3, position = position_stack())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接