在 ggplot 中,您应该使数据采用更长的格式。为此你可以使用pivot_longer
from tidyr
。这样你就可以创建一个像这样的堆积条形图:
df <- data.frame(Valley = c("Hushey", "Kanday", "Thallay"),
Female = c(144, 43, 45),
Young = c(160, 43, 22),
Yearling = c(162, 20, 25))
library(tidyr)
library(dplyr)
library(ggplot2)
df %>%
pivot_longer(cols = -Valley) %>%
ggplot(aes(x = Valley, y = value, fill = name)) +
geom_col()
或者使用以下方法绘制分面图facet_wrap
像这样:
df %>%
pivot_longer(cols = -Valley) %>%
ggplot(aes(x = name, y = value)) +
geom_col() +
facet_wrap(~Valley)
Created on 2023-01-23 with reprex v2.0.2 https://reprex.tidyverse.org