【问题标题】:Order geom_bar by groups按组排序 geom_bar
【发布时间】:2020-09-07 20:46:50
【问题描述】:

我是 R 的新手。我可以订购图例,但我无法按我的意愿订购图形(生产、过程、组织、标记)。我想像这个图例(图像图表)一样对图表进行排序。我正在使用此代码。它只能重新排序,但我没有找到一个好的解决方案。谢谢

ggplot(grado,aes(Label,Grado,fill=as.factor(InnoCat)))+
  geom_bar(position = "dodge",stat="identity")+
  facet_wrap(~InnoCat,nrow=4, scales = "free_y")+
  coord_trans() +
  scale_fill_manual("Leyenda",
                    values = c(
                      "Mark." = "#d982d4",
                      "Org." = "#667ee8",
                      "Proc." = "#53c24f",
                      "Produc." = "#e6914c"
                    )) +
  guides(fill = guide_legend(reverse = TRUE))

数据示例(grado是我的数据集的名称)

structure(list(Nodo = c("P1", "P2", "P3", "P4", "P5", "P6", "P7", 
"P8", "P9", "P10", "P11", "Cooperativas", "Cursos o ferias", 
"Empresas", "Familia y Amigos", "Grupos de Consumo", "Instituciones", 
"Investigación", "Organizaciones", "Técnicos"), Grado = c(0.2, 
0.2, 0.4, 0.4, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.45, NA, 0.45, 
NA, NA, NA, NA, 0.09, 0.18), InnoCat = c("Produc.", "Produc.", 
"Produc.", "Produc.", "Produc.", "Produc.", "Produc.", "Produc.", 
"Produc.", "Produc.", "Produc.", "Produc.", "Produc.", "Produc.", 
"Produc.", "Produc.", "Produc.", "Produc.", "Produc.", "Produc."
), Label = c("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", 
"P9", "P10", "P11", "COOP", "EVEBT", "EMPR", "FA", "GC", "ADMON", 
"INV", "ORG", "TEC")), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

  • 能否请您在问题中包含您的数据,以使您的问题可重现。试试dput(grado。有关如何将可重现数据放入问题的指导,请查看stackoverflow.com/questions/5963269/…?特别是以下部分:“生成最小数据集”和“复制您的数据”。
  • 请将您的数据集添加为数据框 - 而不是表格 - 试试 dput(head(grado, 20))。这应该使您的问题可重现。
  • 我认为它已经准备好了。感谢您在我的第一篇文章中的耐心等待
  • 好的,干得好!现在的问题是您只有 InnoCat 的数据:“Product”。所以你的图表是不可重现的。您需要一个示例数据集,其中包括表示 InnoCat 中每个值的数据行。你的完整数据集有多大?也许尝试过滤您的数据集以获取 Nodo 的三个值

标签: r ggplot2 geom-bar


【解决方案1】:

您可以将 InnoCat 转换为具有所需顺序的级别的因子变量。

grado$InnoCat <- factor(grado$InnoCat, levels = c("Produc.", "Proc.", "Org.", "Mark."))

那么您不必反转图例。

ggplot(grado,aes(Label,Grado,fill=InnoCat))+
  geom_bar(position = "dodge",stat="identity")+
  facet_wrap(~InnoCat,nrow=4, scales = "free_y")+
  coord_trans() +
  scale_fill_manual("Leyenda",
                    values = c(
                      "Mark." = "#d982d4",
                      "Org." = "#667ee8",
                      "Proc." = "#53c24f",
                      "Produc." = "#e6914c"
                    ))

【讨论】:

  • 完美运行。非常感谢。
猜你喜欢
  • 2021-12-02
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
相关资源
最近更新 更多