Add number of observations (Fehler in FUN(X[[i]], ...) : Objekt 'y' nicht gefunden)

Hi!
I have a dataframe 3 variables, and I did a geom_bar. I try to add the number of observations (variable value), but I always get an error (Fehler in FUN(X[[i]], ...) : Objekt 'y' nicht gefunden). The first two lines of plotting work.

My data:

library(dplyr)
library(tidyverse)
library(ggplot2)
library(ggpubr)
library(reshape2)

xy <- data.frame(c("1","2","3","4","5","6","7","8","9"),c(79,2058,11584,2469,527,260,77,10,6),c(532,38,10247,4700,1037,409,89,5,13))
colnames(xy) <- c("Kategorie","x","y")
xy <- melt(xy, id = "Kategorie")

Plotting and trying to add the number of observations:

ggplot() + 
  geom_bar(data = xy, aes(x = Kategorie, y=value, fill = variable), position = "dodge", stat = "identity")+ 
  scale_x_discrete(breaks = 1:9, name = "Kategorie (min)", labels = c("keine Hst/\nAngabe", "0", "1-5", "6-15", "16-30", "31-60", "61-120", "121-180", ">180")) +
 geom_text(aes(label=value),nudge_x=0, nudge_y=250,size=12.5)
  # geom_text(data = label_Histo0, aes(label = textlabel,color=NULL, y=y),size=3)
  # geom_text(aes(label = y))
  # geom_text(aes(label=paste(value)), size=5, hjust=-.6, vjust=1.5) 

Here is the image, how it looks right now. Above the bars, I would like to add the number of observations:

I hope, I was clear enough, explaining my problem.

Yours,
Isabella

This is not the error in your provided code: if I try to run your code I get value not found. It makes sense, since you're providing data=xy in geom_bar(), so geom_text() does not have the data. Similarly, the x and y aesthetics are only given to geom_bar(), so geom_text() will be missing them. The solution is simple: put the values needed by both in the initial call to ggplot().

ggplot(data = xy, aes(x = Kategorie, y=value)) + 
  geom_bar(aes(fill = variable), position = "dodge", stat = "identity") +
  geom_text(aes(label=value))

That way, data, x and y are defined for both bar and text, whereas fill and label are only defined for one geom.

You will still get a problem though: since you used position = "dodge" for geom_bar(), you need to indicate that dodging to geom_text() so that the labels are aligned with the bars. So you need to map an aesthetic to variable in geom_text() too. This should give you what you want:

ggplot(data = xy, aes(x = Kategorie, y=value)) + 
  geom_bar(aes(fill = variable), position = "dodge", stat = "identity")+ 
  scale_x_discrete(breaks = 1:9, name = "Kategorie (min)", labels = c("keine Hst/\nAngabe", "0", "1-5", "6-15", "16-30", "31-60", "61-120", "121-180", ">180")) +
  geom_text(aes(label=value, group=variable), position = position_dodge(.9))

Thanks a lot, now its working!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.