3
# Loading data
data(CPS85, package = "mosaicData")

# Count the number of females and males in each sector
plotdata <- group_by(CPS85,sector) %>%
  count(sex)

# Print the data
print(plotdata)

# Construct a ggplot object according requirement above and assign it to 'plt'
plt <- ggplot(plotdata,
              aes(x = sector,
                  y = n))+
  geom_col(aes(fill=sex))+
  geom_text(aes(label=n),
            position = position_stack(vjust = 0.5))+
  labs(x = "",
       y = "Number of persons",
       title = "")


# Display the stacked bar chart
plt

enter image description here

enter image description here

But I want the number in this stacked bar chart be like: enter image description here

How could I change my vjust to make the number in the middle of the stacked bar

Quinten
  • 35,235
  • 5
  • 20
  • 53
Jane_IDK
  • 65
  • 7
  • Try moving your `fill = sex` from `geom_col()` to `ggplot(aes())`. That is `ggplot(plotdata,aes(x = sector,y = n,fill = sex)) + geom_col() + ...` – benson23 Apr 14 '22 at 13:02

1 Answers1

4

First use geom_bar and set stat = "identity". After that use position = position_stack(vjust = 0.5). You can use the following code:

# Construct a ggplot object according requirement above and assign it to 'plt'
plt <- ggplot(plotdata,aes(x = sector, y = n, fill = sex))+
  geom_bar(stat="identity")+
  geom_text(aes(label=n), position = position_stack(vjust = 0.5))+
  labs(x = "",
       y = "Number of persons",
       title = "")


# Display the stacked bar chart
plt

Output:

enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • 1
    In this case it's completely fine to use `geom_col` (like the OP does), the issue here is the position of the `fill` argument. – benson23 Apr 14 '22 at 13:19