r - Adding total on top of stacked bar graphs -


i creating stacked bar graph in ggplot2. have 2 questions:

how can change scale of y-axis , data labels such shows in units of 1000 instead of 1? there way can make totals of counts show on top of each bar? e.g., show 94 (thousand) in bold above bar 1 , 122 (thousand) above bar 2.

library(ggplot2) library(dplyr)  #creating dataset my.data <- data.frame(dates = c("1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014"),                       fruits=c("apple", "orange", "pear", "berries", "watermelon", "apple", "orange", "pear", "berries", "watermelon"),                        count=c(20000, 30000, 40000, 2000, 2000, 30000, 40000, 50000, 1000, 1000))  #creating positon data labels my.data <-        my.data %>%       group_by(dates) %>%       mutate(pos=cumsum(count)-0.5*count)  #plotting data ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+             geom_bar(stat="identity")+       geom_text(data=subset(my.data, count>10000), aes(y=pos, label=count), size=4) 

here's way create plot. first, calculate sum of count grouped dates.

sum_count <-    my.data %>%   group_by(dates) %>%   summarise(max_pos = sum(count)) 

this new data frame can used plotting sum on top of bars. changing y-axis units of 1000 achieved dividing values 1000.

ggplot(data = my.data, aes(x = dates, y = count / 1000))+         geom_bar(stat = "identity", aes(fill = fruits))+   geom_text(data = subset(my.data, count > 10000),              aes(y = pos / 1000, label = count / 1000 ), size = 4) +   geom_text(data = sum_count,              aes(y = max_pos / 1000, label = max_pos / 1000), size = 4,             vjust = -0.5) 

enter image description here


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -