ggplot-堆叠的geom_bar-将每个x按y重新排序

时间:2019-09-05 09:29:07

标签: r ggplot2

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

enter image description here

但是问题似乎是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)

1 个答案:

答案 0 :(得分:0)

使用@kath的help,我设法解决了问题

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))