首页 文章

ggplot按值排序facet标签

提问于
浏览
2

使用下面的数据框 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 回答

  • 2

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

    您必须创建以下功能,以便管理构面的顺序:

    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

  • 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

相关问题