資料概述:27 個樣本點(條形圖)、3 個以顏色顯示的門/組,以及每個站點的不同數量的獨特物種(分為三個門中的 1 個)。
我試圖在每個堆疊列的頂部放置一個數字,顯示在每個樣本站點(條形圖)檢測到的獨特物種的數量。總體目標是顯示從左到右的多樣性(物種數量)下降。我將數字存盤在向量中,我嘗試使用“count”列合并到原始df,然后執行:geom_text(aes(label=count)),結果如下圖,其中物種/面積的計數是在每個欄中重復。幫助!

可以使用的測驗資料:
set.seed(123)
test.data <- data.frame(area = rep(1:27, 3),
cover = c(rnorm(27, mean = 40),
rnorm(27, mean = 10),
rnorm(27, mean = 5)),
phyla = c(rep("c", 27), rep("o", 27), rep("r", 27)))
ggplot(data=test.data, aes(x=area, y = cover,
fill = phyla))
geom_col()
theme_classic()
scale_y_continuous(expand = expansion(mult = c(0, 0.05)),
limits=c(0,75))
scale_fill_manual(
values =c('#a6611a','#dfc27d', '#80cdc1'))
geom_vline(xintercept=c(9.5,18.5, 27.5), linetype="dotted")
#number I want on top of each bar
count = c(14, 17, 15, 15, 15, 12, 18, 14, 13, 14, 12, 14, 12, 11, 13,
9, 11, 10, 5, 4, 4, 6, 7, 6, 6, 6, 5)
uj5u.com熱心網友回復:
您的堆疊條包括 3 個組area,但您只需要一個計數標簽area。正如您所發現的,這可能很棘手,因為ggplot將嘗試為data. 您可以通過將單獨的資料傳遞給geom_col(您的原始資料test.data,有 27 行)和geom_text(我們將為此創建一個新data.frame的 13 行,每個欄一個)來解決這個問題。
我們還需要知道每個條的總高度,以便將每個標簽放在上面。我們可以通過使用dplyr::group_by()和summarize()計算cover每個 x 值 ( ) 內的 y 值 ( ) 的總和來找到這一點area。
library(tidyverse)
# I'm assuming the `count`s in your question are already in the right order
count.data <- test.data %>%
group_by(area) %>%
summarize(label_height = sum(cover)) %>%
mutate(count = c(14, 17, 15, 15, 15, 12, 18, 14, 13, 14, 12, 14, 12, 11, 13,
9, 11, 10, 5, 4, 4, 6, 7, 6, 6, 6, 5)
)
ggplot()
geom_col(data = test.data, aes(x = area, y = cover, fill = phyla))
geom_text(
data = count.data,
aes(x = area, y = label_height, label = count),
nudge_y = 2 # scoot labels up above bar tops
)
theme_classic()
scale_y_continuous(
expand = expansion(mult = c(0, 0.05)),
limits = c(0, 75)
)
scale_fill_manual(values = c('#a6611a', '#dfc27d', '#80cdc1'))
geom_vline(xintercept = c(9.5, 18.5, 27.5), linetype = "dotted")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430460.html
上一篇:繪制一段時間內的財務/投資價值
