【发布时间】:2021-07-18 19:36:46
【问题描述】:
我的情况似乎不符合之前关于 ggplot2 中堆叠条形内顺序的任何讨论。
我知道堆叠条和图例中两个组件的顺序遵循分配给“fill =”的因子变量的级别。但是我的数据集对于某些级别既有正值,也有其他级别的负值。负值堆积条内的顺序似乎颠倒了级别的顺序。
请允许我用一个例子来说明:
d <- data.frame(
group=c(rep(1,4),rep(2,4),rep(3,4)),
category=c(rep(c("male_for","male_against","female_for","female_against"),3)),
n=c(rep(c(2,-2),6))
)
d$category <- factor(d$category,c("male_for","female_for","male_against","female_against"))
ggplot(d)+ geom_bar(aes(group,n,fill=category),stat="identity")
click here to see the image (not sure why it doesn't embed. sorry
如您所见,因子变量“类别”中的级别顺序为male_for、female_for、male_against、female_against。传说中的顺序也是如此。但是,我猜由于反对组的负值,图表下半部分的堆叠顺序与因子中定义的水平相反。
谁能找出条形图下半部分仍遵循图例中的顺序(即因子中定义)的解决方案?
非常感谢!
【问题讨论】:
标签: r ggplot2 stacked-chart