web-dev-qa-db-ja.com

ggplot2の積み上げ棒グラフにデータ値を表示する

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") 

enter image description here

これらのデータ値を各部分の中央に表示したいと思います。この点で助けていただければ幸いです。ありがとう

96
MYaseen208

ggplot 2.2.0 からは、geom_textposition = position_stack(vjust = 0.5)を使用してラベルを簡単にスタックできます。

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))

enter image description here

また、「position_stack()position_fill()は、グループ化の逆の順序で値をスタックするようになりました。これにより、デフォルトのスタック順序が凡例と一致します。」


古いバージョンのggplotに対して有効な回答:

以下に、バーの中点を計算する1つの方法を示します。

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)

Resultant chart

161
Ramnath

ハドリーが述べたように、積み上げ棒グラフのラベルよりもメッセージを伝える効果的な方法があります。実際、棒グラフ(各カテゴリ)は軸を共有しないため、積み上げグラフはあまり効果的ではないため、比較は困難です。

ほとんどの場合、これらのインスタンスで2つのグラフを使用し、共通の軸を共有することをお勧めします。あなたの例では、全体の合計を表示してから、各カテゴリが特定の年に貢献した割合を表示すると仮定しています。

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)

これにより、次のような2パネルディスプレイが表示されます。

Vertically stacked 2 panel graphic

頻度値を追加する場合は、テーブルが最適な形式です。

22
AndrewMinCH