我如何在ggplot2中的分组条形图列上放置标签

问题描述 投票:2回答:2

我在将百分比和计数标签放置在分组的条形图上时遇到麻烦。标签当前堆叠在一起(see link for image)。我认为这是因为我一直在参考堆叠Barplot的示例代码。我尝试将position=position_dodge(width=1)添加到geom_text来堆叠标签,但是收到以下警告:

警告:忽略未知的美学:位置不知道如何为PositionDodge / Position / ggproto / gg类型​​的对象自动选择比例。默认为连续。错误:美学必须是有效的数据列。问题的美学:位置= position_dodge(宽度= 1)。您是否输入了数据列的名称错误或忘记添加stat()?

这是我使用泰坦尼克号数据集的代码:

data("titanic_train")
head(titanic_train, 6)

library(dplyr)
library(ggplot2)

titanic_train$Survived <- as.factor(titanic_train$Survived)

summary = titanic_train %>% group_by(Survived, Sex) %>% tally %>% mutate(pct = n/sum(n))

ggplot(summary, aes(x=Sex, y=n, fill=Survived)) + geom_bar(stat="identity", position="dodge") + geom_text(aes(label=paste0(sprintf("%1.1f", pct*100),"%\n", n)), colour="black")

非常感谢您对此问题的帮助!预先谢谢你。

r ggplot2 label position bar-chart
2个回答
1
投票

您可以只将position = position_dodge(width = 1)添加到您的geom_text呼叫中,但不在aes之外。您的错误是由于尝试将position...放入aes引起的。

library(dplyr)
library(ggplot2)
library(titanic)

ggplot(summary, aes(x = Sex, y = n, fill = Survived)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = paste0(sprintf("%1.1f", pct * 100), "%\n", n)),
            colour = "black",
            position = position_dodge(width = 1)) +
  coord_cartesian(ylim = c(0, 550))

enter image description here


0
投票

我想分享一个示例,您可以通过使用数据来复制它

数据

df <- data.frame(
  x = factor(c(1, 1, 2, 2)),
  y = c(1, 3, 2, 1),
  grp = c("a", "b", "a", "b")
)

情节

ggplot(data = df, aes(x, y, group = grp)) +
  geom_col(aes(fill = grp), position = "dodge") +
  geom_text(
    aes(label = y, y = y + 0.05),
    position = position_dodge(0.9),
    vjust = 0
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.