我有一个这种形式的R数据帧:(第一,第二,...是行名;A,B,...是列名称)
A B C D E
first 30 0 0 0 0
second 0 20 120 0 0
third 0 40 100 0 0
fourth 0 0 0 30 60我希望ggplot()用x轴上的行名和y轴上的行和绘制一个条形图,这些行和应该按列头类别进行颜色堆叠,并带有数字标签,因此对于上面的数据如下所示:

发布于 2021-08-13 15:54:18
您应该将行名作为变量添加到您的数据框中,并将您的数据转换为长格式,以便ggplot可以处理它。像这样的东西很接近你的意思,我认为:
yourDataFrame %>%
mutate(Label = rownames(df)) %>% # add row names as a variable
reshape2::melt(.) %>% # melt to long format
ggplot(., aes(x = Label, y = value, fill = variable)) +
geom_bar(stat='identity')发布于 2021-08-13 15:54:58
我想你要找的东西是这样的:
df %>%
rownames_to_column(var = 'x') %>%
pivot_longer(-x) %>%
filter(value > 0) %>%
mutate(x = factor(x, levels = c('first', 'second', 'third', 'forth'))) %>%
ggplot(aes(fill = forcats::fct_rev(name), y = value, x = x, label = value)) +
geom_bar(position="stack", stat="identity") +
geom_text(aes(label=value)) +
theme(legend.title = element_blank())

数据:
structure(list(A = c(30L, 0L, 0L, 0L), B = c(0L, 20L, 40L, 0L
), C = c(0L, 120L, 100L, 0L), D = c(0L, 0L, 0L, 30L), E = c(0L,
0L, 0L, 60L)), class = "data.frame", row.names = c("first", "second",
"third", "forth")) -> dfhttps://stackoverflow.com/questions/68774806
复制相似问题