可复制的示例:
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")
答案 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")
或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")
答案 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")