使用ggplot2中的facet_grid和coord_flip删除未使用的级别

时间:2016-11-14 12:18:20

标签: r ggplot2 facet

我有一个数据框df

df<- structure(list(Categorie = structure(c(1L, 1L, 2L, 2L, 4L, 4L, 
3L, 1L, 1L, 2L, 2L, 4L, 4L, 3L, 1L, 1L, 2L, 2L, 4L, 4L, 3L, 1L, 
1L, 2L, 2L, 4L, 4L, 3L, 1L, 1L, 2L, 2L, 4L, 4L, 3L, 1L, 1L, 2L, 
2L, 4L, 4L, 3L, 1L, 1L, 2L, 2L, 4L, 4L, 3L, 1L, 1L, 2L, 2L, 4L, 
4L, 3L), .Label = c("Age classes", "Climate", "Nutrient availability", 
"PFT"), class = "factor"), Sub_categories = structure(c(7L, 4L, 
6L, 1L, 3L, 2L, 5L, 7L, 4L, 6L, 1L, 3L, 2L, 5L, 7L, 4L, 6L, 1L, 
3L, 2L, 5L, 7L, 4L, 6L, 1L, 3L, 2L, 5L, 7L, 4L, 6L, 1L, 3L, 2L, 
5L, 7L, 4L, 6L, 1L, 3L, 2L, 5L, 7L, 4L, 6L, 1L, 3L, 2L, 5L, 7L, 
4L, 6L, 1L, 3L, 2L, 5L), .Label = c("Continental", "DBF", "ENF", 
"Intermediate-Old", "Low-High", "Temperate", "Young"), class = "factor"), 
    Variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 
    3L, 3L, 3L, 3L, 3L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 4L, 4L, 4L, 4L, 
    4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 
    6L, 6L), .Label = c("Age", "Clay content", "GPP", "GPP*Age", 
    "GPP*P", "GPP*P trend", "N availability", "SPI"), class = "factor"), 
    Importance = c(19.2, 23.7, 45.2, 45.7, 39, 66.8, 34.8, 10.9, 
    16.2, 9.2, 6.3, 15.7, 2.1, 10, 13.2, 7.1, 6.1, 3.8, 2.4, 
    7.3, 5.2, 6.4, 10, 6.6, 3.7, 2.9, 5.8, 8.4, 17.7, 0, 6.1, 
    5.2, 8.4, 2.8, 6.7, 11.8, 21.1, 9.8, 21.9, 20, 6.3, 13.5, 
    2.3, 7.6, 3.9, 1.3, 3.9, 0.4, 3.8, 10.9, 7.5, 4.5, 5.8, 0.3, 
    2.5, 9.4)), .Names = c("Categorie", "Sub_categories", "Variable", 
"Importance"), class = "data.frame", row.names = c(NA, -56L))

我想通过做一个facet_grid来绘制我的数据。使用CategorieSub_categories个变量。我运行以下命令行:

library(ggplot2)

ggplot(data = var_Imp) + 
  geom_bar(mapping = aes(x = Variable, y = Importance, fill=Variable), width = 1, stat= "identity", position = "stack") + 
  coord_flip() +
  facet_grid(Categorie~Sub_categories,  scales="free", space="free", shrink=TRUE, drop=TRUE)+ 
  theme_bw(base_size = 14, base_family = "Helvetica")+
  theme(axis.ticks.length=unit(-0.25, "cm"), 
        legend.position="none", 
        legend.box="horizontal",
        legend.key = element_blank(),
        legend.text=element_text(size=14), 
        axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")), 
        axis.text.y = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")),
        axis.ticks.y=element_blank())+
  xlab("") +
  ylab("Relative contribution [%]")+ 
  scale_fill_brewer(type = "div")

但是,仍然会绘制某些方面没有信息的水平,尽管它们不应该,因为它中没有信息。我认为scales="free"space="free"参数可以完成这项工作,但显然不是。任何人都知道如何在没有未使用的级别的情况下绘制数据?谢谢

1 个答案:

答案 0 :(得分:0)

我不知道ggplot2中的特定命令。两种可能的选择:

1)本文ggplot2: How to force the number of facets with too few plots?

中提出的任何选项

2)以.svg(或其他矢量格式)导出绘图,使用inkscape或任何其他程序打开它并删除空面