[英]Ordering barchart in R with facet_wrap and two variables
我的意圖是使用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")
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")
或者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")
使用以下代碼: 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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.