# 在ggplot2中显示堆积条形图上的数据值

``Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4)) Category <- c(rep(c("A", "B", "C", "D"), times = 4)) Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251) Data <- data.frame(Year, Category, Frequency) library(ggplot2) p <- qplot(Year, Frequency, data = Data, geom = "bar", fill = Category, theme_set(theme_bw())) p + geom_text(aes(label = Frequency), size = 3, hjust = 0.5, vjust = 3, position = "stack")` `

### 2 Solutions collect form web for “在ggplot2中显示堆积条形图上的数据值”

`ggplot 2.2.0`标签可以很容易地通过在`geom_text`使用`position = position_stack(vjust = 0.5)``geom_text`

` `ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) + geom_bar(stat = "identity") + geom_text(size = 3, position = position_stack(vjust = 0.5))` `

` `library(ggplot2) library(plyr) # calculate midpoints of bars (simplified using comment by @DWin) Data <- ddply(Data, .(Year), transform, pos = cumsum(Frequency) - (0.5 * Frequency) ) # library(dplyr) ## If using dplyr... # Data <- group_by(Data,Year) %>% # mutate(pos = cumsum(Frequency) - (0.5 * Frequency)) # plot bars and add text p <- ggplot(Data, aes(x = Year, y = Frequency)) + geom_bar(aes(fill = Category), stat="identity") + geom_text(aes(label = Frequency, y = pos), size = 3)` `

` `library(grid) library(gridExtra) library(plyr) # create a new column with proportions prop <- function(x) x/sum(x) Data <- ddply(Data,"Year",transform,Share=prop(Frequency)) # create the component graphics totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + xlab("") + labs(title = "Frequency totals in given Year") proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) + geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + labs(title = "Proportion of total Frequency accounted by each Category in given Year") # bring them together grid.arrange(totals,proportion)` `

• 在R中使用ggplot2创build“雷达图”（aka star plot; spider plot）
• R - 检测向量是否至less有1个NA的最快方法？
• 用于访问列表或数据框元素的和]符号之间的区别
• 确切地了解data.table何时是另一个data.table的引用（vs另一个副本）
• 我怎么能把一个转换的规模在ggplot2的右侧？
• RE：使用ggplot2将各个栏上的数字alignment
• 将SPSS文件读入R
• R中一个模型matrix中所有级别的因子
• 如何从vector中删除多个值？
• 如何打印（纸张）一个很好格式的dataframe
• 在ggplot2中心绘图标题