[英]How to order facets based on facet_wrap from Y values?
is there a way to reorder those facets based on their Y value (aka count
) in decreasing order dynamically - without hardcoding the order (given a similar column to package
with hundreds of levels?有没有办法根据它们的 Y 值(又名count
)以降序动态重新排序这些方面 - 无需对顺序进行硬编码(给定与package
类似的列,具有数百个级别?
library(cranlogs)
library(tidyverse)
tidyverse_downloads <- cran_downloads(
packages = pkgs,
from = "2017-01-01",
to = "2017-06-30") %>%
tibble::as_tibble() %>%
group_by(package)
tidyverse_downloads %>%
ggplot(aes(x = date, y = count)) +
#geom_hline(yintercept = 0, color = "grey40") +
geom_line() +
#geom_smooth(method = "loess") +
theme_minimal() +
facet_wrap(~ package, scale = "free_y",ncol = 2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
What I have tried was to use the package library(tidytext) and scale_y_reordered
我尝试的是使用 package 库(tidytext)和scale_y_reordered
tidyverse_downloads %>%
mutate(count = tidytext::reorder_within(count, date, package)) %>%
tidytext::scale_y_reordered() +
ggplot(aes(x = date, y = count)) +
geom_line() +
theme_minimal() +
facet_wrap(~ package, scale = "free_y",ncol = 2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
however, that doesn't produce any outcome.但是,这不会产生任何结果。 Im doing something wrong I guess.我猜我做错了什么。 Appreciate any help感谢任何帮助
You can sum the total downloads of each package to gather the factor levels in decreasing order.您可以将每个 package 的总下载量相加,以按降序收集因子水平。
library(cranlogs)
library(tidyverse)
pkgs <- c('dplyr', 'broom', 'ggplot2', 'purrr')
tidyverse_downloads <- cran_downloads(
packages = pkgs,
from = "2017-01-01",
to = "2017-06-30") %>%
tibble::as_tibble()
tidyverse_downloads %>%
group_by(package) %>%
summarise(count = sum(count)) %>%
arrange(desc(count)) %>%
pull(package) -> levels
levels
#[1] "ggplot2" "dplyr" "purrr" "broom"
Assign the levels in package
according to levels
above.根据以上级别分配package
中的levels
。
tidyverse_downloads %>%
mutate(package = factor(package, levels)) %>%
ggplot(aes(x = date, y = count)) +
geom_line() +
theme_minimal() +
facet_wrap(~ package, scale = "free_y",ncol = 2) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.