ggplot按值排序facet标签

时间:2018-05-06 15:37:20

标签: r ggplot2

使用如下所示的数据框df,我可以使用分面绘制条形图。

text <- "
make,var,value
fiat,mileage,2.1
astom,mileage,1.8
fiat,disp,1.4
astom,disp,1.7
"
df <- read.table(textConnection(text), sep = ",", header = TRUE)

ggplot(df, aes(x=make, y=value) ) +
  geom_bar(stat = 'identity') +
  facet_wrap(~ var, scales = "free", ncol=1)

这给出了如下图。

enter image description here

但是,我希望x轴标签按照var的值的降序排序 - 在上面的例子中mileage var,fiat应该在之前显示astom - 我怎么做到的?

2 个答案:

答案 0 :(得分:2)

这是受以下github存储库启发的另一种方法:https://github.com/dgrtwo/drlib/blob/master/R/reorder_within.R

您必须创建以下功能,以便管理方面&#39;顺序:

reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
    new_x <- paste(x, within, sep = sep)
    stats::reorder(new_x, by, FUN = fun)
}


scale_x_reordered <- function(..., sep = "___") {
    reg <- paste0(sep, ".+$")
    ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}

然后您可以将它们应用于您的数据:

ggplot(mydata, aes(reorder_within(firstFactor, desc(value), secondFactor), value)) +
    geom_bar(stat = 'identity') +
    scale_x_reordered() +
    facet_wrap(~ secondFactor, scales = "free_x",ncol=1) +
    xlab("make")

这就是结果: enter image description here

答案 1 :(得分:0)

我建议您使用github上的这篇文章启发以下解决方案:https://github.com/tidyverse/ggplot2/issues/1902,即使ggplot2包的作者已弃用此方法。

您的数据:

text <- "
firstFactor,secondFactor,value
fiat,mileage,2.1
astom,mileage,1.8
fiat,disp,1.4
astom,disp,1.7
"
mydata <- read.table(textConnection(text), sep = ",", header = TRUE)

这是用于按升序获取值的代码:

mydata <- mydata %>% 
    ungroup() %>% 
    arrange(secondFactor,value) %>% 
    mutate(.rn=row_number()) # Add a row number variable which allows you to manage the re-ordered labels deriving from the combination of your factors
ggplot(mydata, aes(x=.rn, y=value)) +
    geom_bar(stat = 'identity') +
    facet_wrap(~ secondFactor, scales = "free", ncol=1) +
    scale_x_continuous(  # This handles replacement of .rn for x
        breaks = mydata$.rn,     # you have to recall your data frame
        labels = mydata$firstFactor
    )

这是情节: enter image description here