如何在ggplot2中制作单个堆积的条形图 [英] how to make single stacked bar chart in ggplot2
本文介绍了如何在ggplot2中制作单个堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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")
运行上面的代码会给我以下错误:
Running the above code gives me the following error:
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
我正在寻找创建类似于此的堆叠式条形图:
I'm looking to create a stacked barchart similar to this:
推荐答案
您需要为x轴创建一个虚拟变量.然后使用与geom_bar(stat = "identity")
相似的geom_col
来绘制堆叠的条形图,然后使用geom_text
将文本放到条形上.
You need to create a dummy variable for x-axis. Then use geom_col
which is similar to geom_bar(stat = "identity")
to plot the stacked barplot + geom_text
to put the text on the bar.
您显示的图使用了ggthemes
程序包中的theme_economist
.
The plot you showed used theme_economist
from the ggthemes
package.
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软件包(v0.2.0.9000)创建于2018-08-26.
Created on 2018-08-26 by the reprex package (v0.2.0.9000).
这篇关于如何在ggplot2中制作单个堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文