r - 更改 ggplot2 中给定图表中堆叠条形图的顺序

标签 r ggplot2

一段时间以来,我一直在努力更改给定图表中堆积条形图的顺序。

我确实找到了其他几个讨论 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 之间)对基因进行分组: Example1

这里我们有三个组,我们可以很容易地将其识别为 (i) A>(B or C),(ii) B>(A or C) 和 (iii) C>(A or 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)

ExampleCircularBarPlot

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

最佳答案

我不确定我是否理解,但这就是您要找的吗?

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

enter image description here

关于r - 更改 ggplot2 中给定图表中堆叠条形图的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55226397/

相关文章:

R Plotly 具有 NA 宽度的抖动箱线图

r - 使用 str_detect 提取字符串的值

r - ggplot2:根据填充值为某些点设置alpha = 0

r - 添加 geom_rect 时对象消失

r - 用点绘制植被样线

r - 使用列向量索引多维表

r - SMOTE - 多类

r - 将数据映射到数据框中的列的更好方法?

r - ggplot2 : How to reduce the width AND the space between bars with geom_bar

r - ggplot 使图例符号变细