abiyug abiyug - 2 months ago 19
R Question

ggplot anotate when x values are characters

I would like to 'annotate' a text on the top right hand corner of ggplot2 bar chart that has character for x axis and numeric for y axis. All the documentation I see is that, to annotate a text, both x and y coordinates have to be given numeric value.

Here is an example chart:-

Here is the data frame

df1 <- data.frame( p=c("a","b","c","a","b","c"),
v=c(10,9,8,6,5,2),
u=c("aa","bb","cc","aa","bb","cc")
)


summarized data frame

df2 <- df1 %>% select(p, v) %>% group_by(p) %>% summarise_each(funs(sum))


bar plot

p <- ggplot(data = df2, aes(p, v, label = v)) +
geom_bar(stat = "identity", position = "dodge") +
geom_text(position = position_dodge(.9), vjust = -1, fontface = "bold", size = 5)

p

Answer

You should be able to do it just putting the location inside of aes(). This worked for me (unless I am misunderstanding your intent):

ggplot(data = df2, aes(p, v, label = v)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(position = position_dodge(.9),  vjust = -1, fontface = "bold", size = 5) +
  geom_text(aes(x = "c", y = 15, label = "Here I am"))

enter image description here