gpt4 book ai didi

r - 如何在ggplot2中制作单个堆积的条形图

转载 作者:行者123 更新时间:2023-12-04 10:33:56 27 4
gpt4 key购买 nike

Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"), Proportion = c(40, 30, 10, 15, 5))
Ancestry %>%
ggplot(aes(y = Proportion, fill = Race)) +
geom_bar(stat="identity", colour="white")

运行上面的代码给我以下错误:
Warning in min(x, na.rm = na.rm) :
no non-missing arguments to min; returning Inf
Warning in max(x, na.rm = na.rm) :
no non-missing arguments to max; returning -Inf
Warning in min(diff(sort(x))) :
no non-missing arguments to min; returning Inf
Warning in x - width/2 :
longer object length is not a multiple of shorter object length
Warning in x + width/2 :
longer object length is not a multiple of shorter object length
Error in data.frame(list(y = c(40, 30, 10, 15, 5), fill = c(3L, 1L, 2L, :
arguments imply differing number of rows: 5, 2947

我正在寻找创建类似于此的堆叠式条形图:

enter image description here

最佳答案

您需要为x轴创建一个虚拟变量。然后使用类似于geom_colgeom_bar(stat = "identity")绘制堆叠的条形图+ geom_text将文本放在条形图上。

您显示的情节使用了theme_economist包中的ggthemes

library(tidyverse)

Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"),
Proportion = c(40, 30, 10, 15, 5))

Ancestry <- Ancestry %>%
mutate(Year = "2006")

ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
geom_col() +
geom_text(aes(label = paste0(Proportion, "%")),
position = position_stack(vjust = 0.5)) +
scale_fill_brewer(palette = "Set2") +
theme_minimal(base_size = 16) +
ylab("Percentage") +
xlab(NULL)

library(ggthemes)

ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
geom_col() +
geom_text(aes(label = paste0(Proportion, "%")),
position = position_stack(vjust = 0.5)) +
theme_economist(base_size = 14) +
scale_fill_economist() +
theme(legend.position = "right",
legend.title = element_blank()) +
theme(axis.title.y = element_text(margin = margin(r = 20))) +
ylab("Percentage") +
xlab(NULL)

reprex package(v0.2.0.9000)创建于2018-08-26。

关于r - 如何在ggplot2中制作单个堆积的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52032323/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com