0

I have a dataframe of housing data, but had to make another dataframe where need to sum the housing type depend on where the area of the house, which there are 2 types of houses in 3 different areas.

df <- na.omit(n[, c("matssvaedi", "teg_eign_s_i")])
counts <- df %>%
  group_by(matssvaedi, teg_eign_s_i)%>%
  summarise(count = n())
df1 <- ggplot(counts, aes(x = matssvaedi, y = count))
df1 + geom_bar(aes(fill = teg_eign_s_i), stat = "identity", position = 'dodge') + geom_text(aes(label = count), color="black",vjust = 0.01, size = 3) + scale_fill_brewer(palette = "Paired") + theme_classic()

enter image description here

zephryl
  • 14,633
  • 3
  • 11
  • 30

1 Answers1

1

I'm assuming that your question is "how do I position the text on top of the corresponding bar?". In that case, you can add a position argument to geom_text() in the same way you specify a position for geom_bar(). For example, see this small reprex:

counts <- mtcars |> 
  group_by(cyl, vs) |> 
  summarise(count = n())
df1 <- ggplot(counts, aes(x = factor(cyl), y = factor(count)))
df1 + geom_bar(aes(fill = vs), stat = "identity", position = 'dodge') + 
  geom_text(aes(label = count, group = vs,), 
            position = position_dodge(width = .9),
            color="black",vjust = 0.01, size = 3)

You can use the vjust argument in geom_text() to move the text slightly higher or lower depending on what you want. This gives:

Bar chart

nrennie
  • 1,877
  • 1
  • 4
  • 14
  • important to mention that the standard dodge is .9 in `position_dodge()`. I'd generally avoid combining methods `position = "dodge"` and `position = position_dodge()` for exactly that reason that you might get unexpected results. – tjebo Feb 17 '23 at 07:49
  • and another small extra comment: (fighting windmills here): instead of geom_bar(stat = "identity") you can use the shorter and easier to read: `geom_col()` – tjebo Feb 17 '23 at 07:51
  • Thankyou for the help. and @tjebo, what is teh different interms of position = "dodge" and osition = position_dodge()? – Nouvan Shebubakar Feb 17 '23 at 12:59
  • @NouvanShebubakar position = "dodge" is simply a shorthand for convenience that invokes the function position_dodge with its defaults (i.e., it is equivalent to position = position_dodge(). However, using the latter might come with different arguments (e.g., a different dodge), which you are not able to pass to the first. – tjebo Feb 17 '23 at 17:46