Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adjust the position of each text to the top center of its grouped vertical bar plot columns in ggplot2

By the code below, I generate a grouped bar plot below:

df <- data.frame(Person = c("Mr.A","Mr.B"), Cats = c(3,4), Dogs = c(1,2))
data.m <- melt(df, id.vars='Person')

ggplot(data.m, aes(Person, value)) + 
  geom_bar(aes(fill = variable), width = 0.4, position = position_dodge(width=0.5), stat="identity") +
  geom_text(
    aes(x = Person, y = value, label=value), 
    position = position_dodge(width=1),
    # position = 'dodge', 
    # hjust=-1, 
    vjust=-0.25) +
  theme(legend.position="top", 
        legend.title = element_blank(),
        axis.title.x=element_blank(), 
        axis.title.y=element_blank())

enter image description here

Now my question is how could we adjust the text in the middle of each bar column (as the arrows shown in the figure above), I tried by paramters: position=position_dodge(width=1), position='dodge', hjust=-1 and hjust=1, it seems not working. Someone could help? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Reference:

Aligning geom_text in grouped dodged barplot

>Solution :

You need to specify group=variable in geom_text.

ggplot(data.m, aes(Person, value)) + 
  geom_bar(aes(fill = variable), width = 0.4, position = position_dodge(width=0.5), stat="identity") +
  geom_text(
    aes(x = Person, y = value, label=value, group = variable), 
    position = position_dodge(width=0.5),
    # position = 'dodge', 
    # hjust=-1, 
    vjust=-0.25) +
  theme(legend.position="top", 
        legend.title = element_blank(),
        axis.title.x=element_blank(), 
        axis.title.y=element_blank())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading