1

I need to make a horizontal bar chart for a university assignment and I cannot figure out how to make the distance between the bars of the different groups smaller. And my labels to show the value of the bar are not in a correct position and none of my arguments of changing position work somehow.

This is my code:

df <- data.frame(Category = c("A","B", "C", "D", "E", "F"), 
                 Student = c(4.4,3.35,5.96,2.07,4.56,3.55), 
                 Teacher = c(3.21,4.39,5.3,1.8,2.8,3.14))

data.m <- melt(df, id.vars='Category')

#Grouped Bar plot by Person#####

p <- ggplot(data.m, aes(x= reorder(Category, value), y= value)) + 
  geom_bar(aes(fill = variable), width = 0.30, position = position_dodge(width=0.3), stat="identity") +  
  geom_text(aes(label = value), hjust = -0.2, size = 2.5)

p <- p + labs(title = "Students and Teachers")

p <- p + labs(x = "Category", y = "Means")

p <- p + theme_classic()

p <- p + scale_y_continuous(expand=c(0,0))


p <- p + theme(legend.title = element_blank())

p <- p  + scale_fill_brewer(palette="Blues") 

p +  coord_flip() 

This is what it looks like:

enter image description here

I want to align the text labels more nicely as well as decrease the space between the bars of the groups (A,B,C...). What do I have to change in the geom_text command for the labels and what command do I need for changing the space?

benson23
  • 16,369
  • 9
  • 19
  • 38
minervax29
  • 11
  • 2

1 Answers1

2

As a general rule you have to use the same position in geom_text as for geom_bar/col if you want to align labels with bars. Second, to reduce the space between your groups increase the width of the bars (and in position_dodge).

library(ggplot2)

ggplot(data.m, aes(y = reorder(Category, value), x = value)) +
  geom_col(aes(fill = variable),
    position = position_dodge(width = 0.6), width = .6
  ) +
  geom_text(aes(label = value, group = variable),
    hjust = -0.2, size = 2.5,
    position = position_dodge(width = 0.6)
  ) +
  scale_x_continuous(expand = c(0, 0, .05, 0)) +
  scale_fill_brewer(palette = "Blues") +
  theme_classic() +
  labs(title = "Students and Teachers", x = "Category", y = "Means", fill = NULL)

stefan
  • 90,330
  • 6
  • 25
  • 51