使用facet_wrap和两个变量在R中订购条形图

时间:2018-07-24 21:06:58

标签: r ggplot2

我的意图是使用ggplot2和facet_wrap绘制2个“长期”和“非常长期”失业率图表。 我希望按indic ==“ LTU”(facet_wrap的顶部)的顺序升序,因此在顶部的图表中“ LU”和“ MT”将不在右侧。但是我不管理ggplot来正确订购酒吧。有什么建议吗?

可复制的示例:

library(tidyverse)
library(eurostat)

#Long-term unemployment by sex - quarterly average 
une_ltu_q <- get_eurostat("une_ltu_q", stringsAsFactors=FALSE)


df <- une_ltu_q %>% filter(age=="Y15-74",
                          geo %in% c("EU28", "BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR","IT","CY","LV","LT","LU","HU","MT","NL","AT","PL","PT","RO","SI","SK","FI","SE","UK"),
                          sex=="T",
                          s_adj=="SA",
                          time==max(une_ltu_q$time), 
                          unit=="PC_ACT")%>% 
        group_by(indic_em)%>% arrange()



ggplot(data=df, aes(x=reorder(geo, values), y=values))+
        geom_bar(stat = "identity", 
                 position = "dodge", 
                 show.legend = FALSE,
                 fill="steelblue")+
        geom_text(aes(label=values), vjust=-0.5, size=3.5)+
        facet_wrap(~indic_em, ncol=1, scales = "free")

2 个答案:

答案 0 :(得分:2)

reorder有一个FUN ction参数,您可以使用它来更改顺序。默认情况下,您的示例按两个值的mean排序。但是您也可以只取第一个值:

ggplot(data=df, aes(x=reorder(geo, values, "[", 1), y=values))+
  geom_bar(stat = "identity", 
           position = "dodge", 
           show.legend = FALSE,
           fill="steelblue")+
  geom_text(aes(label=values), vjust=-0.5, size=3.5)+
  facet_wrap(~indic_em, ncol=1, scales = "free")

enter image description here

sum

ggplot(data=df, aes(x=reorder(geo, values, sum, na.rm=T), y=values))+
  geom_bar(stat = "identity", 
           position = "dodge", 
           show.legend = FALSE,
           fill="steelblue")+
  geom_text(aes(label=values), vjust=-0.5, size=3.5)+
  facet_wrap(~indic_em, ncol=1, scales = "free")

enter image description here

答案 1 :(得分:1)

使用在https://github.com/dgrtwo/drlib/blob/master/R/reorder_within.R

上找到的代码

我们可以使用这些功能在组内重新排序,以便每个构面都具有升序条。下面是修改后的整合了这些功能的ggplot代码。

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(data=df, aes(x=reorder_within(geo, values, indic_em), y=values))+
geom_col(stat = "identity", 
position = "dodge", 
show.legend = FALSE,
fill="steelblue")+
geom_text(aes(label=values), vjust=-0.5, size=3.5)+
scale_x_reordered()+
facet_wrap(~indic_em, ncol=1, scales = "free")