首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ggplot stacked geom_bar -按y对每个x重新排序

ggplot stacked geom_bar -按y对每个x重新排序
EN

Stack Overflow用户
提问于 2019-09-05 17:29:07
回答 1查看 40关注 0票数 0

我正在尝试为每个x重新排序堆叠的geom_bar,但没有成功。我想要实现的是一个曲线图,其中对于每个x的值,y值从小到大排序。

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

代码语言:javascript
复制
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

下面的代码根本不会改变我的中断。

代码语言:javascript
复制
ggplot(df) + geom_col(mapping = aes(x = q, y = reorder(val, val), fill = typ)) + scale_y_discrete(breaks = 1:10)
EN

回答 1

Stack Overflow用户

发布于 2019-09-05 17:57:39

通过@kath中的help,我设法解决了这个问题

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57802415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档