How do I position bar chart labels at the "base" of bars

Viewed 1946

I want to make a horizontal bar chart with labels on the bars, at their "bases"

dummy <- USArrests
dummy$state <- rownames(USArrests)

ggplot(
  data = dummy,
  aes(
    x = state,
    y = Murder
  )
) +
  geom_bar(
    stat = "identity"
  ) +
  coord_flip() +
  geom_text(
    aes(
      label = state
    ),
    position = position_dodge(1)
  )

This gives me a chart where the labels are at each bar's "tip." enter image description here

How do I move those labels to the "base" of each bar? The left side of each state's name should be at the left side of the bars.

2 Answers

If you were using dodging to try to help with the positioning it's not necessary. Also, geom_col() saves you some typing:

library(hrbrthemes) # devtools::install_git("https://gitlab.com/hrbrmstr/hrbrthemes")
library(ggplot2)

set.seed(1)
data.frame(
  state = state.name,
  murder = sample(1000, length(state.name)),
  stringsAsFactors = FALSE
) -> xdf

ggplot(xdf, aes(state, murder)) +
  geom_col(fill = "#2b2b2b") +
  geom_text(
    aes(y = 0, label = state), 
    color = ft_cols$yellow, hjust = 0
  ) +
  scale_y_continuous(
    expand=c(0,0), label=scales::comma, position = "right"
  ) +
  coord_flip() +
  labs(x = NULL) +
  hrbrthemes::theme_ipsum_rc(grid="X") +
  theme(axis.ticks.y = element_blank()) +
  theme(axis.text.y = element_blank())

enter image description here

But, consider using geom_segment() which gives you a bit more control and doesn't need flipping:

ggplot(xdf, aes(murder, state)) +
  geom_segment(
    aes(xend=0, yend=state), 
    size = 5, color = "#2b2b2b"
  ) +
  geom_text(
    aes(x = 0, label = state), 
    color = ft_cols$yellow, hjust = 0
  ) +
  scale_x_continuous(
    expand=c(0,0), label=scales::comma, position = "top"
  ) +
  labs(y= NULL) +
  hrbrthemes::theme_ipsum_rc(grid="X") +
  theme(axis.ticks.y = element_blank()) +
  theme(axis.text.y = element_blank())

enter image description here

Maybe like this?

+ geom_text(aes(label = state,y = 0),
          position = position_dodge(1),
          hjust = 0)
Related