【问题标题】:Change the order of Stacked Bars within a given chart in ggplot2在ggplot2中更改给定图表中堆积条的顺序
【发布时间】:2019-03-18 16:55:47
【问题描述】:

我一直在努力改变给定图表中堆积条形的顺序。

我确实发现了其他几个关于 ggplot2 堆叠条形图顺序的主题,但是没有一个回答我的具体问题。 (How to change stacking order in stacked bar chart in R?, How to control ordering of stacked bar chart using identity on ggplot2, R: changing color of stacked barplot)

这里有一些可重现的数据来说明我的问题:

df <- data.frame("Gene" = 1:300, "A" = runif(300), "B" = runif(300), "C" = runif(300))

现在让我们按照 A、B 或 C 的最大值对数据帧进行排序。

max.var <- pmax(df$A, df$B, df$C)
df <- df[order(max.var, decreasing=T),]
head(df)

Gene         A         B         C
290 0.1843646 0.9998304 0.4633329
86 0.2595463 0.9977324 0.3269114
18 0.9959791 0.0368044 0.9469783
238 0.9944759 0.5037651 0.6842606
260 0.4355420 0.4844317 0.9934755
3 0.3702984 0.9922708 0.4254061

最后让我们对其进行排序,以便创建 3 个不同的组:第一个重新组合 A 高于 B 和 C 的所有情况,第二个用于 B 高于 A 和 C 的情况,最后一个用于 C 更高的情况比 A 和 B。

max.var <- pmax(df$A, df$B, df$C)
df.ordered <- rbind(df[which(df$A==max.var),], df[which(df$B==max.var),], df[which(df$C==max.var),])
head(df.ordered)

Gene         A         B         C
18 0.9959791 0.0368044 0.9469783
238 0.9944759 0.5037651 0.6842606
235 0.9857518 0.2102292 0.6547545
121 0.9809101 0.5440542 0.4712545
73 0.9791348 0.4560130 0.3859089
252 0.9677200 0.3219051 0.5486373

现在将其绘制为堆积条形图,让我们格式化数据:

df.Toplot <- data.frame("Value" = c(df.ordered$A, df.ordered$B, df.ordered$C), "Var" = factor(rep(c("A", "B", "C"), each=nrow(df)), levels=c("C", "B", "A")), "Gene" = factor(rep(df.ordered$Gene, 3), levels=df.ordered$Gene))
Plot <- ggplot(data=df.Toplot, aes(x=Gene, y=Value, fill=Var)) + geom_bar(stat="identity")
print(Plot)

这段代码给了我一些根据它们的最大值(在 A、B 和 C 之间)对基因进行分组的东西:

这里我们可以很容易地将三个组识别为 (i) A>(B 或 C)、(ii) B>(A 或 C) 和 (iii) C>(A 或 B)。第一组看起来不错,但我希望其他两组看起来像它,这意味着 B 组基因中的第一个条给出了 B 的值,而在 C 组的基因中,第一个条给出了 C 的值。

我知道我可以制作三个单独的图,但我的最终目标是制作一个圆形条形图,我不知道如何使用三个不同的图来做到这一点。

圆形图:

Plot2 <- ggplot(data=df.Toplot, aes(x=Gene, y=Value, fill=Var)) + geom_bar(stat="identity") + coord_polar(start = 0)
print(Plot2)

非常感谢任何帮助,如果有任何不清楚的地方请告诉我,这是我第一次在这里提问!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不确定我是否关注,但这就是你要找的吗?

    Plot <- ggplot(data=df.Toplot, aes(x=Gene, y=Value, fill=Var, group = Value)) + geom_bar(stat="identity")
    print(Plot)
    

    【讨论】:

    • 是的!我不敢相信这很容易。谢谢你(回答,并编辑我的帖子)!
    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多