samyandi
samyandi

Reputation: 151

ggplot labels on bargraph position

I am REALLY sorry if this is a repeated question. But for some reason the answeres previously given did not work for me. I have the following df:

Country<-c("Chile", "Chile", "Finland","Finland")
Taxa<-c("Mammalia","Amphibia","Mammalia","Amphibia")
Loss<-c(0.15, 1, 0.2, 0.75)
df<-data.frame(Country, Taxa, Loss)

I want to display it as a ranking and add lables. This is what I got:

ggplot(df,aes(x=reorder(Country, Loss), y=Loss)) + 
  geom_bar(aes(fill = Taxa), position="dodge", stat="identity") +
  labs(x = "", y = "")+
  ylim(0,1)+
  theme (legend.position="top", legend.title = element_blank(),legend.text = element_text(size = 17),
         axis.text.x  = element_text(size=17), 
         axis.text.y  = element_text(size=17), axis.title.y=element_text(size=17))+
  geom_text(aes(label = Loss), position=position_dodge(width=1))+
  coord_flip()

It works fine! Only that I cannot position the lables like I want. Id prefer for the labels to be next to the bar. I tried playing around with the width and also some vjust and hjustbut the position never changed... What am I doing wrong?

Thank you in advance!!!

Upvotes: 3

Views: 9406

Answers (2)

bVa
bVa

Reputation: 3948

Another solution using vjust and hjust, as you mentionned.

How to use vjust and hjust

I suppose that you want a label per bar, use group = Taxa in the geom_text(aes()).

enter image description here

ggplot(df,aes(x=reorder(Country, Loss), y=Loss)) +   
geom_bar(aes(fill = Taxa), position="dodge", stat="identity") + 
labs(x = "", y = "")+  ylim(0,1)+  theme (legend.position="top", 
legend.title = element_blank(),legend.text = element_text(size = 17),
axis.text.x  = element_text(size=17), axis.text.y  = element_text(size=17), 
axis.title.y=element_text(size=17))+ 
geom_text(aes(x = reorder(Country, Loss), label = Loss, group = Taxa), 
position=position_dodge(width=1), hjust = -1) 
+  coord_flip()

Upvotes: 5

tonytonov
tonytonov

Reputation: 25638

Idea taken from ?geom_text:

ggplot(df, aes(x=reorder(Country, Loss), y=Loss, label = Loss, fill = Taxa)) + 
  geom_bar(position="dodge", stat="identity") +
  geom_text(aes(y = Loss + 0.02), position = position_dodge(0.9), vjust = 0) + 
  coord_flip()

enter image description here

Upvotes: 4

Related Questions