我是使用 Rstudio 的新手,所以我有一些問題想請教。
我想為 10 個地點的物種組成制作比例尺,并在比例尺內添加數字。
結果是這樣的。

我想將物種組成的頻率數放在比例尺內。我一直在嘗試放置geom_text的代碼,但結果根本不合適。
我希望有一個解決這個問題的答案。非常感謝。
這是我的資料,也是我在 R 中運行的編碼。
data <- as.matrix(data.frame(Bng = c(0, 0, 0, 41, 0, 9, 6, 25, 11, 2, 5, 7),
Krs = c(0, 25, 0, 82, 0, 0, 0, 0, 23, 0, 0, 0),
Bny = c(0, 0, 0, 0, 0, 0, 0, 23, 16, 0, 10, 0),
Kmb = c(1, 0, 0, 0, 20, 0, 0, 25, 8, 1, 0, 0),
Sgk = c(0, 0, 0, 18, 0, 2, 0, 11, 0, 0, 0, 0),
Lwb = c(1, 0, 2, 73, 0, 5, 0, 7, 5, 0, 0, 0),
Lws = c(0, 0, 0, 4, 0, 0, 0, 4, 0, 4, 1, 0),
Krp = c(0, 0, 0, 115, 0, 0, 2, 0, 2, 0, 0, 0),
Hrt = c(4, 0, 0, 0, 2, 22, 0, 7, 4, 2, 3, 0),
Gmb = c(0, 2, 0, 42, 2, 0, 0, 1, 6, 4, 3, 0)))
rownames(data) <- c("Cbr", "Csx", "Rax", "Hdd", "Hlv", "Mst", "Mps", "Mbr", "Rfs", "Rbn", "Rct", "Rps")
data
barplot(data)
barplot(prop.table(data, 2))```
library(reshape2)
data_long <- as.data.frame(data)
data_long$subgroup <- rownames(data_long)
data_long <- melt(data_long, id.vars = "subgroup")
library(ggplot2)
ggp <- ggplot(data_long,
aes(x = variable,
y = value,
fill = subgroup))
geom_bar(position = "fill", stat = "identity")
theme_bw()
scale_fill_grey()
ggp
ggp
scale_y_continuous(labels = scales::percent_format())
uj5u.com熱心網友回復:
你可以試試
library(dplyr)
data_long %>%
group_by(subgroup) %>%
mutate(key = sum(value),
value = value/sum(value)
) %>%
filter(value != 0) %>%
ggplot(aes(x = variable,
y = value,
fill = subgroup))
geom_bar(position = "fill", stat = "identity")
theme_bw()
scale_fill_grey()
scale_y_continuous(labels = scales::percent_format())
geom_text(aes(label = value * key), position = position_fill(vjust = .5))

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/360792.html
