【问题标题】:Grouped and categorized barplot in RR中的分组和分类条形图
【发布时间】:2020-04-23 00:06:02
【问题描述】:

我将使用其他人生成的以下数据来解释我需要什么。请运行代码,你会看到你有这个情节:

我需要的是有相同的情节,并且在左侧(除了酶 1 到 4)有酶类别(酶 1 和 3 作为类别 1,酶 2 和 4 作为类别 2)。你能帮我解决这个问题吗?

library(tidyverse)
data_wide <- tibble(ethnicity = c("ethnicity1", "ethnicity2"),
                    enzyme1 = c(-1, -2), 
                    enzyme2 = c(1, 1),
                    enzyme3 = c(1, 2),
                    enzyme4 = c(-1, 1))
data_long <- data_wide %>% 
  pivot_longer(starts_with("enzyme"), "enzyme")

data_long$Category= c("Category1", "Category2", "Category1", "Category2", "Category1", "Category2", "Category1", "Category2")

data_long1=subset(data_long, ethnicity=="ethnicity1")

data_long1[["sign"]] = ifelse(data_long1[["value"]] >= 0, "positive", "negative")

library(ggplot2)
ggplot()+
  geom_col(data = data_long1, aes(x = enzyme, 
                             y = value,fill = sign))+
  geom_hline(aes(yintercept = 0))+
  coord_flip()+
  theme_linedraw()+ geom_bar() + 
  scale_fill_manual(values = c("positive" = "green", "negative" = "red"))

【问题讨论】:

标签: r ggplot2 label bar-chart


【解决方案1】:

一种可能的解决方案是在“类别”的函数中使用facet_grid 对图表进行分面,如下所示:

library(ggplot2)
ggplot(data = data_long1, aes(x = reorder(enzyme, desc(enzyme)), 
                              y = value,fill = sign))+
  geom_col()+
  geom_hline(aes(yintercept = 0))+
  coord_flip(clip = "off")+
  scale_fill_manual(values = c("positive" = "green", "negative" = "red"))+
  facet_grid(Category~., scales = "free_y", switch = "y", space = "free_y")+
  theme(strip.text.y.left = element_text(angle = 0, face = "bold", vjust = 1),
        strip.background = element_blank(),
        strip.placement = "outside",
        axis.title.y = element_blank())

它回答了你的问题吗?

【讨论】:

  • 感谢您的帮助!不知何故很难弄清楚。是否有可能有一个丰富多彩的标识或类别的一些规模?
  • 您能澄清一下您的图表所需的输出是什么吗?我试图通过将每种酶的类别放在左侧同时保持(几乎)相同的情节结构来解决您的问题。请描述您正在寻找的情节类型。
  • 你所了解的情节正是我所需要的。但是,如果类别以粗体或颜色突出显示,并且标签如上所述,就像我在编辑后的图 [2] 中上传的那样,那会更好。谢谢。
  • 它在这里:i.stack.imgur.com/WYOaU.png。我也有 35 个类别,每个类别中酶的数量都不同。如果一类酶的数量多于另一类,则看不到酶的名称。是否可以设置像 panel.spacing 或其他项目来根据每个类别中的项目数更改每个面板的长度,以便可以轻松看到酶的名称?谢谢
  • 我编辑了我的答案。让我知道它是否是您正在寻找的东西。使用spaces = "free_y",该图应根据您在每个类别中的不同酶的数量重新排列,因此它们都应该是可见的。更多信息在这里:ggplot2.tidyverse.org/reference/facet_grid.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
相关资源
最近更新 更多