我有一个看起来像这样的数据集:
a b a_total b_total
dog 3 5 10 8
cat 6 2 12 13
pig 9 3 15 9
我正在尝试使用ggplot制作一个堆叠的条形图,以使每只动物的底部都有“ a_total”,顶部有“ a”。我试过了,但是没有用。
ggplot(df, aes(x = "", y = c("a", "a_total")) + geom_bar(stat= "identity")
我应该怎么做?
我们从行名(rownames_to_column
)创建select
列,再将'a'列与新列一起创建,整形为'long'格式(pivot_longer
)并进行绘制
library(dplyr)
library(tidyr)
library(ggplot2)
df %>%
rownames_to_column('animal') %>%
select(animal, a, a_total) %>%
pivot_longer(cols = -animal) %>%
ggplot(aes(x = animal, y = value, fill = name)) +
geom_bar(stat = 'identity') +
theme_bw()
-输出
另外,这对于a中的“ a”和“ b”都可以完成 facet_wrap
df %>%
rownames_to_column('animal') %>%
pivot_longer(cols = -animal) %>%
mutate(abgrp = substr(name, 1, 1)) %>%
ggplot(aes(x = animal, y = value, fill = name)) +
geom_bar(stat = 'identity') +
theme_bw() +
facet_wrap(~ abgrp)
在中base R
,我们可以使用barplot
barplot(t(df[c('a', 'a_total')]), col = c('red', 'blue'), legend = TRUE)
df <- structure(list(a = c(3L, 6L, 9L), b = c(5L, 2L, 3L), a_total = c(10L,
12L, 15L), b_total = c(8L, 13L, 9L)), class = "data.frame", row.names = c("dog",
"cat", "pig"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句