首页 > 解决方案 > ggplot - 堆叠的 geom_bar - 将每个 x 按 y 重新排序

问题描述

我试图geom_bar为每个堆叠重新排序,x但没有成功。我想要实现的是一个图,其中对于 x 的每个值,y 值从最小到最大排序。像这样的东西:

在此处输入图像描述

然而,问题似乎是ggplot威胁 y 作为离散值而不是连续值,因此我无法更改 y 轴的中断和标签。我试过使用scale_x_discrete没有成功。

library(tidyverse)

df <- data.frame(q= c(rep("2011", 3), rep("2012", 3)), 
                 typ = rep(c("A", "B", "C"), 2), 
                 val = c(7,2,1,2,3,4), stringsAsFactors = F) %>% as_tibble()

ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) 



ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_continuous()
    Error: Discrete value supplied to continuous scale

以下代码根本不会改变我的休息时间。

ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_discrete(breaks = 1:10)

标签: rggplot2

解决方案


在@kath 的帮助下,我设法解决了它

library(tidyverse)

df <- data.frame(q= c(rep("2011", 3), rep("2012", 3)), 
                 typ = rep(c("A", "B", "C"), 2), 
                 val = c(7,2,1,2,3,4), stringsAsFactors = F) %>% as_tibble()

bars <- map(unique(df$q)
            , ~geom_bar(stat = "identity", position = "stack"
                        , data = df %>% filter(q == .x)))

df %>% 
  ggplot(aes(x = q, y = val, fill = reorder(typ,val))) + 
  bars +
  guides(fill=guide_legend("ordering")) + 
  scale_y_continuous(breaks = 1:10, limits = c(0, 10))

推荐阅读