我正在嘗試創建堆疊條形圖但無法創建“堆疊部分”。我希望將我的條形高度作為 gdp_per_capita 列,然后我希望將 gdp_per_capita_agg_percen 列顯示為每列的一部分(這是我的 gdp_per_capita 列的百分比)。為了更清楚地了解國家 1,我需要列值為 3281,然后其中的堆疊部分為 676(占其中的 20.6%)。
下面使用的資料和代碼;
資料
df2
Country_Name gdp_per_capita `Agriculture_GDP%` gdp_per_capita_agg_percen
1 Albania 3281 20.6 676
2 Algeria 3515 9.86 346
3 Bosnia and Herzegovina 3828 8.21 314
4 Croatia 11285 3.90 440
5 Cyprus 24686 2.60 643
6 Egypt, Arab Rep. 2192 13.3 292
當前沒有堆疊的代碼;我閱讀了有關position="stack"在 geom_bar 引數中使用的資訊,但不確定如何在我的 gdp_per_capita_agg_percen 資料中添加堆疊
ggplot(df2, aes(x = as.factor(Country_Name), y = gdp_per_capita, fill = as.factor(Country_Name)))
geom_bar(stat = "identity")
uj5u.com熱心網友回復:
不會稱之為堆疊。但是你可以通過第二次達到你想要的結果geom_col/bar:
library(ggplot2)
ggplot(df2, aes(x = as.factor(Country_Name), y = gdp_per_capita, fill = "GDP"))
geom_col()
geom_col(aes(y = gdp_per_capita_agg_percen, fill = "Agriculture"))

資料
structure(list(Country_Name = c("Albania", "Algeria", "Bosnia and Herzegovina",
"Croatia", "Cyprus", "Egypt, Arab Rep."), gdp_per_capita = c(3281L,
3515L, 3828L, 11285L, 24686L, 2192L), `Agriculture_GDP%` = c(20.6,
9.86, 8.21, 3.9, 2.6, 13.3), gdp_per_capita_agg_percen = c(676L,
346L, 314L, 440L, 643L, 292L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
uj5u.com熱心網友回復:
多次呼叫同一個 geom 不是一個好主意。這通常意味著您需要在繪制資料之前對其進行整形。見下文;
library(tidyverse)
df2 %>%
select(-`Agriculture_GDP%`) %>%
pivot_longer(cols = -"Country_Name") %>%
ggplot()
geom_col(aes(x = as.factor(Country_Name), y = value, fill = name))
scale_fill_manual(labels = c("GDP", "Aggriculture"),
values = scales::hue_pal()(2))
labs(y = "Country", x = "GDP")

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/527524.html
標籤:rggplot2几何学
上一篇:如何在分組的ggplot2條形圖上顯示平均分隔字母?
下一篇:Y軸刻度數以百萬計
