Jenny
Jenny

Reputation: 69

How to position labels on grouped bar plot columns in ggplot2

I am having trouble positioning percentage&count labels on a grouped barplot.

The labels are currently stacked together:

see image

I think this is because I have been referring to an example code for a stacked barplot. I have tried adding position=position_dodge(width=1) to geom_textto unstack the labels, but I have gotten the following warning:

Warning: Ignoring unknown aesthetics: position Don't know how to automatically pick scale for object of type PositionDodge/Position/ggproto/gg. Defaulting to continuous. Error: Aesthetics must be valid data columns. Problematic aesthetic(s): position = position_dodge(width = 1). Did you mistype the name of a data column or forget to add stat()?

Here is the code I have using the Titanic dataset:

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")

How can I resolve this?

Upvotes: 2

Views: 3386

Answers (2)

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

I would like to share an example which you could replicate the same by using your data

data

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

plot

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

Upvotes: 0

Greg
Greg

Reputation: 3670

You can just add position = position_dodge(width = 1) to your geom_text call, but outside of aes. Your error was caused by trying to put position... inside 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

Upvotes: 3

Related Questions