graphics - R ggplot geom_text Aesthetic Length -


i'm working big data setcontaining 1 dummy variable , factor variable 14 levels- sample of have posted here. i'm trying make stacked proportional bar graph using following code:

ggplot(data,aes(factor(data$factor),fill=data$dummy))+ geom_bar(position="fill")+ ylab("proportion")+ theme(axis.title.y=element_text(angle=0)) 

it works great , almost plot need. want add small text labels reporting number of observations of each factor level. intuition tells me should work

labels<-c("n=1853" , "n=392",  "n=181" ,  "n=80",   "n=69",   "n=32" ,  "n=10",    "n=6",    "n=4",    "n=5",    "n=3",    "n=3",    "n=2",    "n=1" )  ggplot(data,aes(factor(data$factor),fill=data$dummy))+ geom_bar(position="fill")+ geom_text(aes(label=labels,y=.5))+ ylab("proportion")+ theme(axis.title.y=element_text(angle=0)) 

but spits out blank graph , error aesthetics must either length one, or same length dataproblems:labels

this doesn't make sense me because know fact length of factor levels same length number of labels muscled in. i've been trying figure out how can print need without creating vector of values number of observations this example, no matter try same aesthetics error.

how this:

library(dplyr)  # create separate data frame of counts count labels counts = data %>% group_by(factor) %>%   summarise(n=n()) %>%   mutate(dummy=na)  counts$factor = factor(counts$factor, levels=0:10)  ggplot(data, aes(factor(factor), fill=factor(dummy))) +   geom_bar(position="fill") +   geom_text(data=counts, aes(label=n, x=factor, y=-0.03), size=4) +   ylab("proportion")+   theme(axis.title.y=element_text(angle=0)) 

your method right idea, labels needs data frame, rather vector. geom_text needs given name of data frame using data argument. then, label argument inside aes tells geom_text column use labels. also, though geom_text doesn't use dummy column, has in data frame or you'll error.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -