[英]R add frequency count labels to ggplot geombar
我有一個像這樣的 plot :
使用以下代碼:
df.m <- reshape2::melt(ngli,id.vars = "Hugo_Symbol")
plot <- ggplot(df.m, aes(x = Hugo_Symbol, y = value, fill=variable)) +
geom_bar(stat='identity') +
#geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
#geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)
theme(axis.text.x=element_text(angle = 90, vjust = 0.5))
我已經嘗試使用注釋代碼添加每個 label 的計數,如下所示:
但它不起作用。 有任何想法嗎? 謝謝!
如果沒有可重現的數據集示例,很難確定您的問題的解決方案是什么。
但是,根據您的代碼,您似乎正在嘗試獲取一個條形圖,表示為每個 x 值觀察到的所有值的總和(使用geom_bar(stat = "identity")
)並添加每個類別的觀察次數和每個x 值與geom_text
。
一種可能的解決方案是在ggplot2
之外計算這些值。 這里,一個使用iris
數據集的例子。 您可以首先以更長的格式重塑您的數據(就像您對melt
所做的那樣),然后計算分組變量和類別的總和和觀察次數(我添加平均值只是為了好玩)
library(tidyr)
library(dplyr)
df <- iris %>% pivot_longer(-Species, names_to = "variable", values_to = "val") %>%
group_by(Species, variable) %>%
summarise(Mean = mean(val),
Sum = sum(val),
count = n())
# A tibble: 12 x 5
# Groups: Species [3]
Species variable Mean Sum count
<fct> <chr> <dbl> <dbl> <int>
1 setosa Petal.Length 1.46 73.1 50
2 setosa Petal.Width 0.246 12.3 50
3 setosa Sepal.Length 5.01 250. 50
4 setosa Sepal.Width 3.43 171. 50
5 versicolor Petal.Length 4.26 213 50
6 versicolor Petal.Width 1.33 66.3 50
7 versicolor Sepal.Length 5.94 297. 50
8 versicolor Sepal.Width 2.77 138. 50
9 virginica Petal.Length 5.55 278. 50
10 virginica Petal.Width 2.03 101. 50
11 virginica Sepal.Length 6.59 329. 50
12 virginica Sepal.Width 2.97 149. 50
然后,您可以 plot 您的條形圖如下使用geom_col
(這與編寫geom_bar(stat = "identity")
相同)並使用position_stack
ZC1C425268E68A974 將您的 label 放在堆疊條形圖上
library(ggplot2)
ggplot(df, aes(x = variable, y = Sum, fill = Species))+
geom_col()+
geom_text(aes(label = count),position = position_stack(0.5))
它回答了你的問題嗎?
如果沒有,請按照本指南提供數據集的可重現示例: 如何制作出色的 R 可重現示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.