【问题标题】:ggplot: geom_bar stacking order and labelsggplot:geom_bar 堆叠顺序和标签
【发布时间】:2017-04-23 07:19:11
【问题描述】:

我正在使用 ggplot 绘制以下数据:

df<- data.frame(name= c("g1","g1","p1","p1"),fc = c(-1.32,-2.11,-1.17,-3.23),fdr = c(.0001,.0001,.07,.0002),cond= c("2v1","3v1","2v1","3v1"))


head(df)
name    fc   fdr cond
 g1  -1.32 .0001 2v1
 g1  -2.11 .0001 3v1
 p1  -1.17   .07 2v1
 p1  -3.23 .0002 3v1

使用ggplot代码:

df$name<- as.factor(df$name)
df$name <- relevel(df$name, as.character(df$name[3]))

ggplot(df, aes(name,fc), group=variable)+
geom_col(aes(fill=factor(as.numeric(fdr)<0.05)), width = 0.98,color="white")+
coord_flip()+scale_fill_manual(values = c("FALSE"= "#00BFC4","TRUE"= "#F8766D"))+
geom_hline(yintercept = 0, colour = "gray" )+
geom_text(aes(label=round(fc,2)),angle = 90, position = position_stack(vjust = 0.5), size =3.5, color= "white")

导致这个情节:

p1 的图似乎颠倒了,-1.17 的条在顶部,而标签仍在底部。我希望灰色条位于底部,标签“1.17”位于中间。 我会很感激我能得到的任何帮助。谢谢

【问题讨论】:

    标签: ggplot2 stacked-chart


    【解决方案1】:

    我建议在data.frame 中设置尽可能多的绘图特征。这将有助于保持 aes 从一层到另一层的一致性。

    library(ggplot2)
    library(dplyr)
    
    df <- data.frame(name = c( "g1",  "g1",  "p1",  "p1"), 
                     fc   = c(-1.32, -2.11, -1.17, -3.23), 
                     fdr  = c(.0001, .0001,   .07, .0002), 
                     cond = c("2v1", "3v1", "2v1", "3v1"))
    
    # use dplyr to set the name and fill factors
    # use the group_by to generate the cumsum for defining where the label should be
    # located.
    df <-
      df %>%
      dplyr::mutate(name = factor(name, levels = c("p1", "g1")),
                    fill = factor(fdr < 0.05, c(TRUE, FALSE), c("fdr < 0.05", "fdr >= 0.05"))) %>%
      dplyr::group_by(name) %>%
      dplyr::mutate(text_y = -cumsum(-fc)) %>%
      dplyr::ungroup()
    
    # the plot
    ggplot(df) +
      aes(x = name, y = fc, fill = fill) + 
      geom_col(width = 0.98, color="white") +
      coord_flip() +
      geom_hline(yintercept = 0, colour = "gray" ) +
      geom_text(mapping  = aes(y = text_y, label = round(fc, 2)),
                angle    = 90,
                color    = "white",
                position = position_stack(vjust = 0.5),
                size     = 3.5,
                color    = "white")
    

    【讨论】:

    • 感谢您的解决方案!我从未使用过 dplyr,所以我不确定你在那里做了什么,但我会阅读手册。谢谢!
    猜你喜欢
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多