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

时间:2018-10-18 08:35:14

标签: r ggplot2 label geom-text

我在使用ggplot2排序数据标签时遇到问题。

不幸的是,关于此主题的其他SE问答不是很有见识的(example),因此我不得不与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))))

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

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 个答案:

答案 0 :(得分:3)

您需要调用position中的geom_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)

enter image description here

答案 1 :(得分: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())

答案 2 :(得分:0)

您可以在邮件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