r - ggplot2 Facet Wrap 按 y 轴重新排序,而不是 x 轴

标签 r ggplot2

我想绘制多面条形图并从左到右从最大到最小值对它们进行排序。我应该能够使用类似的代码来做到这一点:

library(ggplot2)
ggplot(mpg, aes(reorder(cyl, -hwy), hwy)) + 
  geom_col() + 
  facet_wrap(~ manufacturer, scales = "free")

相反,我得到的是按 x 轴排序,恰好是“cyl”,从最小值到最大值。如何按 y 轴降序排列,使其看起来像帕累托图?它也必须是多面的。谢谢你。

最佳答案

这是一种不同的方法,可以使用来自 here 的两个函数直接在 ggplot 中执行。 .我将使用eipi10的例子:

library(tidyverse)
mpg$hwy[mpg$manufacturer=="audi" & mpg$cyl==8] <- 40

dat <- mpg %>% group_by(manufacturer, cyl) %>% 
  summarise(hwy = mean(hwy)) %>% 
  arrange(desc(hwy)) %>% 
  mutate(cyl = factor(cyl, levels = cyl))

职能:
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(dat, aes(reorder_within(cyl, -hwy, manufacturer), y = hwy), hwy) + 
  geom_col() + 
  scale_x_reordered() +
  facet_wrap(~ manufacturer, scales = "free") +
  theme(axis.title=element_blank())

enter image description here

对于升序,您将:reorder_within(cyl, hwy, manufacturer)
没有函数的绘图:
ggplot(dat, aes(cyl, y = hwy)) + 
  geom_col() + 
  facet_wrap(~ manufacturer, scales = "free") +
  theme(axis.title=element_blank())

enter image description here

关于r - ggplot2 Facet Wrap 按 y 轴重新排序,而不是 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48197773/

相关文章:

r - 如何对按索引引用列的数据帧列表应用 lm 函数?

r - 如何在ggplot2的顶部面板边框添加线条

减少 Rmd PDF 中 ggplot 和标题之间的空白

r - R保存来自嵌套的for循环的结果

r - 如何打印没有索引的长列表?

r - 使用字符串名称在功能上创建变量

r - 根据多个条件过滤组内的行

r - 根据 R 中的数据框绘制合适的图形并将其转换为 HTML

r - ggplot2:如何拥有不同颜色的 geom_vline()

r - 如何为 nls 函数找到好的起始值?