2016-01-21 39 views
0

我正嘗試在同一圖形(圖內)中創建具有計數和組級別的堆棧欄。由於組變量具有25個等級,因此我更願意將組等級的名稱(因爲我們有25種不同的顏色,難以可視化)。我從「Showing data values on stacked bar chart in 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(dplyr) 
Data <- group_by(Data,Year) %>% 
mutate(pos = cumsum(Frequency) - (0.5 * Frequency)) 

library(ggplot2) 
#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) 

回答

1

東西沿着這些路線會做的伎倆:

p <- ggplot(Data, aes(x = Year, y = Frequency)) + 
    geom_bar(aes(fill = Category), stat="identity", show.legend = FALSE) + 
    geom_text(aes(label = Frequency, y = pos), size = 3, nudge_y = -25) + 
    geom_text(aes(label = Category, y = pos), size = 3, nudge_y = 25) 

它,只要你喜歡繪製

plot with labels on stacked bars

自定義。

+0

嗨,你能給我一個關於根據它們的頻率重新排序這些細胞的建議。 – shoorideh

+1

在'mutate' *之前,在'dplyr'鏈*中放置'arrange(desc(Frequency))'(對於頂部的最小條;將相反的「desc」移除)。 – alistaire

相關問題