【问题标题】:R barplot color by column while keeping the dataframe orderR barplot 按列显示颜色,同时保持数据框顺序
【发布时间】:2018-10-22 15:30:50
【问题描述】:

我正在尝试在 R 中创建一个条形图,以保持数据的顺序,并用不同的颜色为数据着色。 我的数据是这样的:

row.name  BMP2      type
qaz        4         gf
zaq        3         gf
xsw        5         ds

数据按“类型”列排序。

下面是我得到的情节。我已经指出了我想着色的部分:

我的代码:

 barplot(height = h$BMP2,
          las=3,                                  
          space=1,                                
          main = chosen_gene                         
  )

*使用 ggplot2 的解决方案将不胜感激

【问题讨论】:

  • 没有列BMP2。你的意思是GLIPR1?
  • 是的,抱歉(刚刚创建了几个)

标签: r ggplot2


【解决方案1】:

问题好像是数量多吧。使用基础 R barplot,条形的边框是黑色的,并且使颜色不可见。使用ggplot2 也会发生类似的效果。

所以我会先创建一个更大的数据集。

h <- read.table(text = "
row.name  BMP2    type
qaz        4         gf
zaq        3         gf
xsw        5         ds                  
", header = TRUE)

h <- do.call(rbind, lapply(1:(700/3), function(i) h[sample(nrow(h)), ]))
h <- h[order(h$type), ]
h$row.name <- paste0(h$row.name, seq_along(h$row.name))
h$BMP2 <- sample(20, nrow(h), TRUE)

dim(h)
#[1] 699   3

现在是情节。

根据type 组的长度定义一个颜色向量。然后使用该向量为条形分配颜色。

l <- lengths(split(h$type, h$type))
col <- rep(seq_along(l), l)

barplot(height = h$BMP2,
        las = 3,                                  
        space = 1,                                
        main = "chosen_gene",
        col = col,
        border = NA
)

对于ggplot 图表,首先对"factor" 类的type 列重新排序,以便按组绘制条形图。

library(ggplot2)

h$row.name <- factor(as.character(h$row.name), levels = h$row.name, labels = h$row.name)

ggplot(h, aes(x = row.name, y = BMP2, fill = type)) +
  geom_bar(stat = "identity", position = "dodge")

【讨论】:

  • 第一部分没有奏效,所有的条形图仍然是黑暗的。在 ggplot2 部分中,我不想按行名重新排列,因为我需要按类型对栏进行排序
  • h$type的返回值是多少?至于ggplot 部分,请稍等。
  • h$type 中的每个元素都是一个因素,如果这就是你的意思的话
  • @sahar 完成,看看是不是这样。
  • 很遗憾没有。问题是所有 int 列都可以,我根据类型值得到 1 或 2,但它仍然只显示为黑色
【解决方案2】:

您可以定义一个矢量mycols,让您可以根据需要选择每种条形颜色。根据您的示例数据,如果您希望前 2 个条为蓝色,最后一个为红色:

myids <- 1:nrow(h)
mycols <- ifelse(myids<=2, "blue", "red")
barplot(height = h$GLIPR1,
        las=3,                                  
        space=1,                                
        main = chosen_gene,
        col=mycols, 
        border = NA  # remove the black hairline around each box
)

这里的颜色取决于myid,也就是h的行号,但你可以随意定义其他条件。

【讨论】:

  • 你的条可能太小了,你能试试前 50 行吗?否则,你能分享你的代码吗?
  • 我有 703 行,50 行将是相同的颜色,不管它是否有效,我在上面分享了我的代码并实现了你编写的代码
  • 使用 700 个垂直条,条上的黑色边框会遮挡颜色。在 barplot 函数中添加“border=NA”。 (请参阅上述答案中的编辑)
猜你喜欢
  • 2015-09-10
  • 2021-12-28
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
相关资源
最近更新 更多