【问题标题】:Add color to text in geom_text based on condition根据条件为 geom_text 中的文本添加颜色
【发布时间】:2015-10-06 22:00:33
【问题描述】:

我正在制作一个图,其中 pvalue 使用 geom_text 绘制为文本。 pvalues 在文件pvaluesmir21combined 中给出。

如果值

ggplot(TumorNormalmiR21_5p.m3, aes(X2,value)) + 
  geom_dotplot(aes(fill=variable),binaxis = "y") + coord_flip() +
  theme_bw(base_size=8) +
  theme(axis.text.y=element_text(hjust = 0)) +
  geom_text(aes(x, y, label=FDR, group=NULL),data=pvaluesmir21combined,size=2)


> pvaluesmir21combined

           FDR  x  y
1  p = 8.3e-02  1 13
2  p = 6.3e-05  2 13
3  p = 3.2e-17  3 13
4  p = 4.8e-22  4 13
5  p = 3.1e-10  5 13
6  p = 6.7e-11  6 13
7  p = 3.2e-24  7 13
8  p = 2.1e-06  8 13
9  p = 1.9e-02  9 13
10 p = 9.4e-06 10 13
11 p = 1.5e-03 11 13

【问题讨论】:

  • 将颜色向量指定为element_text。见stackoverflow.com/questions/20609716/…
  • 类似geom_text(aes(x, y, label=FDR, group=NULL, colour=ifelse(as.numeric(sub("p = ", "", FDR)) < 5e-02 , "red", "black")),data=pvaluesmir21combined,size=2)
  • 成功了。然而,它们变成了红色和绿松石色。
  • 你应该使用scale_color_manual或任何其他函数来选择颜色

标签: r text colors ggplot2


【解决方案1】:

你可以试试scale_color_manual这个函数

ggplot(TumorNormalmiR21_5p.m3, aes(X2,value)) + 
 geom_dotplot(aes(fill=variable),binaxis = "y") + coord_flip() +
 theme_bw(base_size=8) +
 theme(axis.text.y=element_text(hjust = 0)) +
 geom_text(aes(x, y, label=FDR, group=NULL, color = ifelse(as.numeric(sub("p = ", "", FDR)) < 5e-02, 0, 1),data=pvaluesmir21combined,size=2) + 
 scale_color_manual(values = c("red", "black"))

查看此链接http://docs.ggplot2.org/0.9.3.1/scale_manual.html

【讨论】:

  • 不知道如何为 data.frame 类型的对象自动选择比例。 eval(expr,envir,enclos)中默认为连续错误:找不到对象'x'
  • 这个有效:geom_text(aes(x, y, label=FDR, colour=colours),data=pvaluesmir21combined,size=2) + scale_color_manual(values=colours) +
  • 颜色
【解决方案2】:

我只想添加另一个替代解决方案,我发现添加 ** 以防 p 值显着(

geom_text(data = pvaluesmir21combined, aes(label = ifelse(as.numeric(sub("p = ", "", FDR)) < 5e-02, "**", " ")), color = "red" ) + 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2021-01-09
    • 1970-01-01
    • 2014-10-22
    • 2022-07-21
    • 2019-05-13
    • 2018-06-19
    相关资源
    最近更新 更多