【发布时间】:2019-10-05 13:52:59
【问题描述】:
一般信息
我正在使用 R 中的 ggplot2 包来绘制一些数据,其中我有兴趣使用 geom_col 将数据框的每一行绘制为单独的条形图。每个条都与应该以相同颜色绘制的组相关,除此之外,我想使用 geom_rect 交替背景颜色,其中背景将跨越多个组。
我还没有弄清楚如何在没有为每个背景单独调用 geom_rect 的情况下绘制背景。在我的真实示例中,我需要执行 24 次 geom_rect 调用,并且肯定有更好的方法(参见标题“Example geom_rect in one call”下的尝试)。
下面是我的一些测试数据的代码,我几乎可以使用它。
我实际上对结果很满意,但我有两个问题。
- 需要有一种更好的方法来调用 geom_rect 调用,并且不会丢失 x 轴上的顺序,这就是为什么标题为“Example geom_rect in one call”下的解决方案不适合的原因只是为了目的。
- 我希望能够控制每个组的条形颜色。通常我会使用 scale_fill_manual(values=c("my_colors")) 但这会覆盖背景中矩形的颜色。
##Generate simul data
gene_list <- c("CHEK2", "AML", "TP53", "AKT1", "ATRX", "CDK4")
df <- data.frame(x = gene_list, y = rnorm(6))
df$grp <- c( rep(c(1),3), rep(c(2), 3) )
df$col <- c( rep(c("grey"),3), rep(c("blue"), 3) )
df_rec <- data.frame(xmin = c("CHEK2", "AKT1"), xmax = c("TP53", "CDK4"), ymin = c(-Inf, -Inf), ymax=c(Inf, Inf), col=c("red", "blue"))
##Reformat order
my_factor <- factor(gene_list, levels = gene_list)
df$x <- my_factor
##Create barplot
ggplot() +
geom_rect(data = df_rec,
aes(
fill=df_rec$col[1],
alpha=),
xmin = as.numeric(df$x[df$x == as.character(df_rec$xmin[1])]) - 0.45,
xmax = as.numeric(df$x[df$x == as.character(df_rec$xmax[1])]) + 0.55,
ymin = -Inf,
ymax = Inf) +
geom_rect(data = df_rec,
aes(
fill=df_rec$col[2],
alpha=1),
xmin = as.numeric(df$x[df$x == as.character(df_rec$xmin[2])]) - 0.45,
xmax = as.numeric(df$x[df$x == as.character(df_rec$xmax[2])]) + 0.45,
ymin = -Inf,
ymax = Inf) +
geom_col(df, mapping = aes(x = x, y=y, fill = as.character(grp)))
一次调用示例 geom_rect
使用上面代码中列出的相同数据。
每当我尝试使用对每个矩形都有限制的 df_rec 时,我都会放松 x 轴上标签的顺序,控制矩形的颜色,并且无法将 geom_rect xmin 和 xmax 位置调整为我在上面的代码中做了没有提示错误“提供给连续刻度的离散值”
(已编辑)我忘了补充一点,将因子的水平设置为具有我想要的 xmin 和 xmax 的顺序仍然无法正确排序条形。
##Reformat order
my_factor <- factor(gene_list, levels = gene_list)
df$x <- my_factor
ggplot() +
geom_rect(data = df_rec,
aes(
alpha=1,
xmin = factor(df_rec$xmin, levels=levels(df$x)),
xmax = factor(df_rec$xmax, levels=levels(df$x)),
ymin = -Inf,
ymax = Inf),
fill = df_rec$col
) +
geom_col(df, mapping = aes(x = x, y=y), fill = df$col)
感谢任何人花时间看这个。
【问题讨论】:
-
这两个图都对我造成了错误。第一个
grp变量似乎丢失了,第二个错误是Error: Aesthetics must be either length 1 or the same as the data (6): fill。准备示例时,应通过重新启动 R、清空环境并在发布前再次运行来对其进行测试。 -
抱歉,我刚刚意识到我在发布之前进行了更新,向 df 数据框添加了两列。由于我已经编辑了上面的代码,这两个示例现在都应该重现结果。