我想以遞減的方式對每個條形中的面進行排序 - > 首先是最高值,然后是下一個,然后是下一個......
一個簡單的例子如下:
library(ggplot)
library(forcats)
mpgtest <- mpg
mpgtest$class <- fct_reorder2(mpgtest$class, mpgtest$manufacturer, mpgtest$cyl)
ggplot(mpgtest, aes(x=manufacturer, y = cyl, fill = class))
geom_col()
facet_wrap(.~year)
在示例中,堆疊的順序不正確。
uj5u.com熱心網友回復:
我對你的例子有點困惑,所以我試著想出一個更直觀的例子。
您需要在繪圖前手動設定條形部分的最小值和最大值。我在這里用 geom_segment 繪制,但你也可以使用 geom_rect。
library(tidyverse)
inventory <-
tibble::tribble(
~month, ~store, ~item, ~stock_count,
"May", "store A", "bananas", 30L,
"May", "store A", "oranges", 10L,
"May", "store A", "mangoes", 10L,
"May", "store A", "kiwis", 4L,
"May", "store B", "bananas", 15L,
"May", "store B", "oranges", 5L,
"May", "store B", "mangoes", 50L,
"May", "store B", "kiwis", 2L,
"June", "store A", "bananas", 30L,
"June", "store A", "oranges", 10L,
"June", "store A", "mangoes", 10L,
"June", "store A", "kiwis", 4L,
"June", "store B", "bananas", 15L,
"June", "store B", "oranges", 5L,
"June", "store B", "mangoes", 50L,
"June", "store B", "kiwis", 2L
)
fruit_colors <- c("bananas" = "yellow2",
"oranges" = "orange2",
"mangoes" = "indianred3",
"kiwis" = "yellowgreen")
inventory %>%
group_by(month, store) %>%
arrange(-stock_count, .by_group = T) %>%
mutate(ymax = cumsum(stock_count),
ymin = lag(ymax, default = 0)) %>%
ungroup() %>%
ggplot()
geom_segment(aes(y = ymin,
yend = ymax,
x = store,
xend = store,
color = item),
size = 10)
scale_color_manual(values = fruit_colors)
facet_wrap(~month)

Created on 2021-10-22 by the reprex package (v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335798.html
