我有以下關于美國和德國青少年編碼技能的資料。我可以輕松顯示他們的條形圖,但我還需要顯示來自每個國家/地區的青少年總數。
DF <- data.frame(code = rep(c("A","B","C"), each = 2),
Freq = c(441,121,700,866,45,95),
Country = rep(c("USA","Germany"),3),
Total = rep(c(1186,1082),3))
ggplot(DF, aes(code, Freq, fill = code)) geom_bar(stat = "identity", alpha = 0.7)
facet_wrap(~Country, scales = "free")
theme_bw()
theme(legend.position="none")
例如,我可以用 和 替換它,而不是顯示 的默認code圖例。感謝您的幫助CountryTotal
uj5u.com熱心網友回復:
這是我的建議:
library(dplyr); library(ggplot2)
DF %>%
add_count(Country, wt = Total) %>%
mutate(Country_total = paste0(Country, ": Total=", n)) %>%
ggplot(aes(code, Freq, fill = code)) geom_bar(stat = "identity", alpha = 0.7)
facet_wrap(~Country_total, scales = "free")
theme_bw()
theme(legend.position="none")

做你要求的事情會采取不同的方法,因為你所描述的資料不會嚴格地是一個 ggplot2 圖例(它解釋了一個變數如何映射到一個圖形美學),而是一個顯示在繪圖旁邊的表格或注釋。這可以單獨生成并使用patchwork或grid包添加到圖中。
例如:
library(patchwork); library(gridExtra)
ggplot(DF, aes(code, Freq, fill = code)) geom_bar(stat = "identity", alpha = 0.7)
facet_wrap(~Country, scales = "free")
theme_bw()
theme(legend.position="none")
tableGrob(count(DF, Country, wt = Total))
plot_layout(widths = c(2,1))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/482170.html
上一篇:改變ggplot中的y軸比例
