R语言 基于1个以上变量的分组条形图

q5lcpyga  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(114)

我试着在R中对条形图进行分组,让它们基于两个变量,type(税收、收入和增值税)和group(A和B)。我成功地基于类型进行分组,但是当我试着分组时,它似乎不起作用。

plot <- ggplot(data=df, aes(x=Person, y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_grid(~type, scales="free_x")

我得到的结果是这样的:

想要的结果应该是这样的,组在底部:

dput的输出:

dput(head(df.new))
structure(list(Person = c("Jon", "Bill", "Maria", "Ben", "Tina", 
"lisa"), Amount = c(23, 41, 32, 58, 26, 54), type = c("Tax", 
"Tax", "VAT", "Income", "Tax", "Income"), group = c("A", "B", 
"B", "A", "B", "A"), FIAT = c("BTC", "GBP", "BTC", "EURO", "USD", 
"USD")), row.names = c(NA, 6L), class = "data.frame")
mklgxw1f

mklgxw1f1#

我看到两个选项,都是{ggh 4x}包提供的,我个人更喜欢facet_nested方法,因为它更容易编码,看起来更整洁,而且没有警告(我不知道它来自哪里,我假设从独特的群体和缺乏所有级别的最后一个方面),但有-据我所知-没有简单的方法来切换侧从嵌套带只。这当然可以实现,但将(海事组织)需要一些grob黑客。

选项1 - facet_nested

library(ggh4x)
#> Loading required package: ggplot2
ggplot(data=df, aes(x=Person, y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_nested(~ type + group, scales="free_x")

选项2 -引导轴嵌套

## make a combined group from your x Person and group
ggplot(data=df, aes(x=interaction(Person, group, sep = "&"), y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_grid(~ type, scales="free_x") +
  scale_x_discrete(guide = guide_axis_nested(delim = "&"), name = NULL)
#> Warning in min(diff(position)): no non-missing arguments to min; returning Inf

创建于2023-03-22带有reprex v2.0.2

相关问题