【问题标题】:Arranging subgroups in ggplot [duplicate]在ggplot中安排子组[重复]
【发布时间】:2015-01-27 06:46:22
【问题描述】:

我有这组数据

data<-read.table("http://pastebin.com/raw.php?i=Vb8S91LX", header=TRUE)

当我使用 ggplot 绘制它们时,X 轴子组自动排列为每个 x 变量的 GSi_GSNor

我使用的代码是

ggplot(data, aes(x=gene, y=value,fill=as.factor(group))) + 
   geom_bar(stat='identity', position='dodge') +
   geom_errorbar(aes(ymin=value, ymax=value+std),position=position_dodge(0.9), width=.2) +
   scale_fill_grey() +
   theme_bw() + 
   xlab("gene symbol")+
   ylab("value") + 
   theme(text = element_text(size=20, face="bold"),
   axis.text.x = element_text(vjust=2))

我的问题: 我怎么能颠倒它们“我的意思是子组而不是 X 轴”,以便我可以将它们作为Nori_GSGS

数据

data <- structure(list(gene = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), .Label = c("C3", "C4A", "C4B", 
"C5", "C6", "C7", "C8A", "C8B", "C8G", "C9"), class = "factor"), 
    group = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("GS", "i_GS", "Nor"), class = "factor"), 
    value = c(149L, 43L, 19L, 0L, 0L, 0L, 0L, 0L, 0L, 15L, 192L, 
    68L, 67L, 51L, 14L, 13L, 0L, 9L, 7L, 41L, 407L, 70L, 71L, 
    170L, 45L, 47L, 19L, 43L, 24L, 125L), std = c(26L, 17L, 33L, 
    0L, 0L, 0L, 0L, 0L, 0L, 1L, 51L, 3L, 5L, 45L, 12L, 11L, 0L, 
    8L, 6L, 29L, 73L, 6L, 6L, 84L, 16L, 30L, 17L, 30L, 10L, 2L
    )), .Names = c("gene", "group", "value", "std"), class = "data.frame", row.names = c(NA, 
-30L))

【问题讨论】:

  • 这听起来像你需要定义你的group 变量see?factor 的级别,否则它们是按字母顺序绘制的。搜索关于更改 ggplot 中变量顺序的 SO- 有很多示例
  • 我添加了代码,谢谢
  • 更改factordata$group &lt;- factor(data$group, levels=c("Nor", "i_GS", "GS")) 的级别,然后在您的ggplot 调用中更改fill=group
  • 其实这是一个更好的副本:stackoverflow.com/questions/3253641/…
  • user20650 是的,我在发帖前看到了那个。正如我在帖子中指出的那样,我想对子组而不是 x 轴本身进行排序,谢谢

标签: r rstudio


【解决方案1】:

只需在 ggplot() 之前添加:

data$group <- factor(data$group, levels = c("Nor", "i_GS", "GS"))

想法是 ggplot 从因子中读取它们在数据框中的排列方式。因此,如果您想以不同的方式查看它们,则必须重新排列数据框中的因子。

【讨论】:

  • A. Val ,,, 不幸的是,添加 scale_x_discrete(limits = c("Nor", "i_GS", "GS")) 不起作用
  • 好吧,在我有机会看到你的代码之前,这是一次疯狂的尝试。
  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
  • @Werner;但这是一个解决方案 - 我错过了什么谢谢?
  • @A.Val。 ;我认为 ggplot 按字母顺序排列,而不是它们在数据框中的顺序
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2017-11-08
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
相关资源
最近更新 更多