如何使图例元素沿数据帧行排序但不重新排序?

时间:2019-04-23 03:38:49

标签: r ggplot2

我想沿着定义的颜色矢量从左到右填充每个条形颜色。但是图例将重新排列颜色。如何将图例元素显示为数据框行中的顺序?我举一个例子,如下:

df <- data.frame(a=1:4,b=2:5,c=c('b','d','a','e'),d=factor(1:4))
col <- c('#a6cee3', '#1f78b4','#6a3d9a', '#b2df8a')

我想要的条形颜色顺序

ggplot(df)+
  geom_col(aes(x=a,y=b,fill=d))+
  scale_fill_manual(values=col)

如果使用列c填充颜色,则图例将重新排序为'a','b','c','d'。看起来颜色参数传递给图例,然后填充条引用图例。因此,条形颜色混乱。如何避免图例元素重新排序?它可以显示为“ d”,“ c”,“ b”,“ a”吗? 如果不是,条形颜色能否与col一致?

ggplot(df)+
  geom_col(aes(x=a,y=b,fill=c))+
  scale_fill_manual(values=col)

2 个答案:

答案 0 :(得分:2)

您可以使用forcats::fct_inorder()c转换为因子,其水平按当前顺序:

ggplot(df)+
    geom_col(aes(x=a,y=b,fill=forcats::fct_inorder(c)))+
    scale_fill_manual(values=col)

答案 1 :(得分:1)

rule EverybodyCanReadEverything { description: "Allow all participants read access to all resources" participant: "org.sc.product.SampleParticipant" operation: READ resource: "org.sc.product.*" action: ALLOW } rule EverybodyCanSubmitTransactions { description: "Allow all participants to submit transactions" participant: "org.sc.product.SampleParticipant" operation: CREATE resource: "org.sc.product.SampleTransaction" action: ALLOW } rule OwnerHasFullAccessToTheirAssets { description: "Allow all participants full access to their assets" participant(p): "org.sc.product.SampleParticipant" operation: ALL resource(r): "org.sc.product.SampleAsset" condition: (r.owner.getIdentifier() === p.getIdentifier()) action: ALLOW } rule SystemACL { description: "System ACL to permit all access" participant: "org.hyperledger.composer.system.Participant" operation: ALL resource: "org.hyperledger.composer.system.**" action: ALLOW } rule NetworkAdminUser { description: "Grant business network administrators full access to user resources" participant: "org.hyperledger.composer.system.NetworkAdmin" operation: ALL resource: "**" action: ALLOW } rule NetworkAdminSystem { description: "Grant business network administrators full access to system resources" participant: "org.hyperledger.composer.system.NetworkAdmin" operation: ALL resource: "org.hyperledger.composer.system.**" action: ALLOW } 列的通常顺序是字母顺序。如果我们需要对此行为进行任何更改,请以我们需要的自定义顺序指定的factor调用factor

levels

运行OP的df$c <- factor(df$c, levels = unique(df$c)) 代码后,其输出将如下所示

enter image description here