編輯
從約ggplot 2.1.0,geom_text
得到一個position_fill
/position_stack
,從而不再有必要計算,也不使用AY審美定位標籤(請參見原件下面的pos
)。
dt <- read.table(text = "time grpmember
1 TRUE
1 TRUE
1 TRUE
1 FALSE
1 FALSE
1 FALSE
2 FALSE
2 TRUE
2 TRUE
2 TRUE", header=TRUE)
dt$time <- as.factor(dt$time)
library(ggplot2)
library(dplyr)
dtSummary = dt %>%
group_by(time, grpmember) %>%
summarise(count = n()) %>%
mutate(Percent = paste0(sprintf("%.1f", count/sum(count) * 100), "%"))
ggplot(dtSummary, aes(x = time, y = count, fill = grpmember, label = Percent)) +
geom_bar(position = "stack", stat = "identity") +
geom_text(position = position_stack(vjust = .5))
原始
我不能完全確定你所追求的,但這種計算包含計數,標籤彙總表(即百分比)和位置的標籤(在每個片段的中點);然後繪製該圖。
dt <- read.table(text = "time grpmember
1 TRUE
1 TRUE
1 TRUE
1 FALSE
1 FALSE
1 FALSE
2 FALSE
2 TRUE
2 TRUE
2 TRUE", header=TRUE)
dt$time <- as.factor(dt$time)
library(ggplot2)
library(dplyr)
dtSummary = dt %>%
# Get the counts
group_by(time, grpmember) %>%
summarise(count = n()) %>%
# Get labels and position of labels
group_by(time) %>%
mutate(Percent = paste0(sprintf("%.1f", count/sum(count) * 100), "%")) %>%
mutate(pos = cumsum(count) - 0.5 * count)%>%
mutate(pos = cumsum(count) - 0.5 * count) %>%
mutate(grpmember = factor(grpmember),
grpmember = factor(grpmember, levels = rev(levels(grpmember))))
ggplot(dtSummary, aes(x = time, y = count, fill = grpmember)) +
geom_bar(stat = "identity") +
geom_text(aes(y = pos, label = Percent))
你能提供你計數的原始數據?如果我理解正確,那麼您會希望y軸以原始計數值表示,同時每個堆棧的百分比也顯示出來? –
如果你想要一個100%疊加的條形圖,其中每個系列的百分比總和爲100%,ggplot2可以做到這一點,而不需要轉換數據:http://stackoverflow.com/questions/3619067/stacked -bar-chart-in-r-ggplot2 -y-axis-and-bars-as-percent-of-counts但是,就帶有這種圖表的百分比標籤而言,您可能需要隨時轉換爲彙總表提出並計算標籤的位置。 –