r - ggplot add percentage labels based on x-axis variables -
i've ggplot shows counts of tweets brands label overall percentage. done link: show % instead of counts in charts of categorical variables
# plot ggplot of brands ggplot(data = test, aes(x = brand, fill = brand)) + geom_bar() + stat_bin(aes(label = sprintf("%.02f %%", ..count../sum(..count..)*100)), geom = 'text', vjust = -0.3)
next, plot based on brand , sentiment, labels bars of each brand totalling 100%. however, have difficulty amending code this. able please? also, possible change colours neu blue , pos green?
# plot ggplot of brands , sentiment ggplot(data = test, aes(x = brand, fill = factor(sentiment))) + geom_bar(position = 'dodge') + stat_bin(aes(label = sprintf("%.02f %%", ..count../sum(..count..)*100)), geom = 'text', position = position_dodge(width = 0.9), vjust=-0.3)
here's dput of 100 rows of data's brand , sentiment column
structure(list(brand = structure(c(3l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 2l, 1l, 1l, 2l, 3l, 4l, 4l, 1l, 2l, 1l, 2l, 1l, 3l, 3l, 3l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 2l, 1l, 3l, 5l, 2l, 1l, 2l, 1l, 1l, 2l, 2l, 1l, 4l, 5l, 5l, 1l, 1l, 2l, 3l, 1l, 1l, 4l, 1l, 2l, 1l, 2l, 1l, 1l, 1l, 1l, 2l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 2l, 2l, 1l, 1l, 3l, 2l, 2l, 2l, 3l, 3l, 3l, 1l, 1l, 4l, 1l, 1l), .label = c("apple", "samsung", "sony", "bb", "htc", "nokia", "huawei"), class = "factor"), sentiment = structure(c(2l, 1l, 3l, 1l, 2l, 3l, 1l, 1l, 3l, 1l, 1l, 2l, 3l, 1l, 1l, 3l, 2l, 1l, 3l, 1l, 3l, 3l, 3l, 2l, 1l, 2l, 1l, 1l, 1l, 1l, 1l, 1l, 2l, 1l, 3l, 2l, 1l, 1l, 2l, 2l, 1l, 1l, 1l, 1l, 2l, 3l, 1l, 3l, 3l, 3l, 3l, 3l, 3l, 1l, 3l, 1l, 1l, 1l, 3l, 3l, 2l, 1l, 1l, 2l, 3l, 3l, 1l, 3l, 2l, 1l, 3l, 1l, 2l, 3l, 3l, 3l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 3l, 1l, 3l, 1l, 1l, 3l, 3l, 3l, 3l, 3l, 2l, 1l, 1l, 1l, 1l, 3l), .label = c("neg", "pos", "neu"), class = "factor")), .names = c("brand", "sentiment"), class = c("data.table", "data.frame"), row.names = c(na, -100l), .internal.selfref = <pointer: 0x0000000003070788>)
posting hack far far far ggplot2
idiomatic way this, if posts more ggplot2
way this, should accept idiomatic method.
so i'm creating dummy data set include information you've calculated using ..count../sum(..count..)*100
, plotting on top of bar plot using geom_text
temp <- as.data.frame(table(test$brand, test$sentiment)) temp <- merge(temp, as.data.frame(table(test$brand)), = "var1", all.x = t) names(temp) <- c("brand", "sentiment", "freq", "count") library(ggplot2) ggplot(data = test, aes(x = brand, fill = factor(sentiment))) + geom_bar(position = 'dodge') + geom_text(data = temp, aes(x = brand, y = freq, label = sprintf("%.02f %%", freq/count*100)), position = position_dodge(width = 0.9), vjust=-0.3)
this not same plot because provided subset of data
Comments
Post a Comment