ggplot x axis labels

Hi. Why does the following not display x axis labels? And how do I display count numbers with geom_text above each bar? Thank you.

library(ggplot2)
account <- c(1,2,3,4,1,2,3,1,2)
repay <- c(0,1,1,1,0,0,0,0,0)
table(account)

binned_account <- cut(account, breaks=c(1,2.01,3.01,4), labels=c("<= 0","small","large"), include.lowest=TRUE)
table(binned_account)

df <- data.frame(cbind(binned_account, repay))
df$repay <- factor(df$repay)
ggplot(data=df) +
geom_bar(aes(x=binned_account,fill=repay), position="dodge") +
scale_fill_manual(values=c("red", "blue")) +
scale_x_discrete(labels=c("<= 0","small","large"))

The issue appears to stem from the fact that binned_account is a factor with 3 levels. If you set the limits to match the levels within scale_x_discrete(), the labels appear.

str(binned_account)
#>  Factor w/ 3 levels "<= 0","small",..: 1 1 2 3 1 1 2 1 1

ggplot(data=df) +
  geom_bar(aes(x=binned_account,fill=repay), position="dodge") +
  scale_fill_manual(values=c("red", "blue")) +
  scale_x_discrete(limits = 1:3, labels=c("<= 0","small","large"))

Here is one way to add the counts above the bars, which creates an adjustment factor to handle the "dodge" position. Alter the x adjustment (0.25) and y adjustment (0.5) as desired.

library(dplyr)

counts = count(df, binned_account, repay) |>
  group_by(binned_account) |>
  mutate(max_rows = n()) |>
  ungroup() |>
  # adjust the x position
  mutate(xadjust = case_when(
    max_rows == 1 ~ 0,
    as.character(repay) == '0' ~ -0.25, 
    TRUE ~ 0.25))

ggplot(data=df) +
  geom_bar(aes(x=binned_account,fill=repay), position="dodge", ) +
  scale_fill_manual(values=c("red", "blue")) +
  scale_x_discrete(limits = 1:3, labels=c("<= 0","small","large")) +
  geom_text(data = counts, aes(x = binned_account + xadjust, y = n + 0.5, label = n)) +
  labs(y = 'count')

Created on 2023-05-30 with reprex v2.0.2

2 Likes

That's perfect. Thank you.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.