每个离散 x 值在 geom_bar 中的不同填充顺序

tal*_*lat 4 r ggplot2

我有这个 ggplot:

图片

我想要做的是以降序更改cat2每个不同cat1-category 中的顺序share

  • 对于 cat1 == Z:i将首先出现,因为它在 that 中的份额最大cat1,其次是k,然后j等等。
  • 对于 cat1 == Y:j会排在最前面,因为它在 that 中所占的份额最大cat1,其次是h, k, f,g
  • 依此类推,适用于所有 cat1 类别。

我知道我可以通过定义因子水平来控制顺序,但是由于我需要在不同的 cat1 类别中使用不同的顺序,我不确定如何执行此操作。

有人可以启发我吗?


df <- structure(list(cat2 = c("i", "k", "j", "h", "g", "j", "h", "k", 
"f", "g", "j", "h", "k", "f", "g", "i", "k", "j", "h", "f"), 
    cat1 = c("Z", "Z", "Z", "Z", "Z", "Y", "Y", "Y", "Y", "Y", 
    "X", "X", "X", "X", "X", "W", "W", "W", "W", "W"), share = c(0.254318086442458, 
    0.217254586570476, 0.13303361614456, 0.107317457057957, 0.0796390207719751, 
    0.255762968963295, 0.198921069216629, 0.177295815678624, 
    0.100770340584133, 0.0971042138291394, 0.222007778896866, 
    0.177174367182501, 0.156891912894117, 0.097677432116308, 
    0.0975337223454565, 0.503295513011454, 0.154491050393999, 
    0.114284166914891, 0.0802892036069214, 0.0549053589320047
    ), pos = c(0.477447245936265, 0.108627293285238, 0.283771394642756, 
    0.658265017686473, 0.751743256601439, 0.305177300160272, 
    0.532519319250233, 0.088647907839312, 0.779469237979754, 
    0.680531960773118, 0.26789580234255, 0.467486875382234, 0.0784459564470585, 
    0.702446497377094, 0.604840920146212, 0.520422973814617, 
    0.0772455251969995, 0.211633133851444, 0.812215332123805, 
    0.879812613393268)), .Names = c("cat2", "cat1", "share", 
"pos"), class = "data.frame", row.names = c(NA, -20L))

library(ggplot2)
ggplot(df, aes(cat1, share)) + 
  geom_bar(stat = "identity", aes(fill = cat2)) + 
  geom_text(aes(label = cat2, y = pos)) +
  coord_flip()
Run Code Online (Sandbox Code Playgroud)

注意:我目前的想法是,也许可以使用将级别设置为 1st、2nd、3rd、4th、5th 的新类别来完成,但如果我使用它来填充,例如iforZjfor 的不同 cat2 值Y将具有相同的填充颜色,因为它们在我不想要的相应 cat1 类别中排名第一。

eip*_*i10 5

您可以通过创建一个新的因子列来做到这一点,我们称之为cat3,基于cat1cat2。根据cat1和设置此列的因子排序share。然后使用这个新的cat3因子列作为group美学来设置条的堆叠顺序。

在下面的代码中,arrange设置排序。我们share在 的每个级别内分别对数据框进行排序cat1。现在数据框按照我们想要的顺序排列。然后我们cat3通过粘贴cat1cat2一起创建并将级别的顺序设置为数据框的当前排序顺序。最后,ggplot我们将其cat3用作group美学来设置geom_bar.

另一个补充是使用position_stack(vjust=0.5)来设置标签位置,而不是y美学。

library(tidyverse)

df %>% 
  arrange(cat1, share) %>% 
  mutate(cat3 = factor(paste(cat1, cat2), levels=paste(cat1, cat2))) %>%
  ggplot(aes(cat1, share, group=cat3)) + 
    geom_bar(stat = "identity", aes(fill = cat2)) + 
    geom_text(aes(label = cat2), position=position_stack(vjust=0.5)) +
    coord_flip()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明