Reputation: 151
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 hjust
but the position never changed... What am I doing wrong?
Thank you in advance!!!
Upvotes: 3
Views: 9406
Reputation: 3948
Another solution using vjust
and hjust
, as you mentionned.
I suppose that you want a label per bar, use group = Taxa
in the geom_text(aes())
.
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
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()
Upvotes: 4