简体   繁体   中英

How to cluster points based on both x and y value ranges in ggplot

I have dataset of RNA expression values of different samples. I applied linear fitting and Bayes statistics on them and then plotted log fold change ("LogFC") against "P.Value" to obtain the following ggplot. Now I want to colour values with "LogFC" < -2 or > 2 and values with "P.Value" <0.05 both with a different colour than the rest of values. How can I do that?

ggplot 火山图的 logFc 和表达基因的 P 值

While you could indeed plot subsets of the data as layers, you could also make the colour aesthetic a nested ifelse() statement. You'll get the correct legend too. Example below:

library(ggplot2)
set.seed(0)

df <- data.frame(
  logFC = rt(10000, 10),
  pvalue = runif(10000)
)

ggplot(df, aes(logFC, log10(pvalue))) +
  geom_point(
    aes(colour = ifelse(is.na(pvalue) | pvalue > 0.05 | abs(logFC) < 2, "n.s.",
                        ifelse(logFC >= 2, "Up", "Down")))
  ) +
  scale_colour_manual(values = c("limegreen", "grey50", "dodgerblue"),
                      name = "Category") +
  scale_y_continuous(trans = "reverse")

Created on 2020-09-17 by the reprex package (v0.3.0)

Seems you used a geom_point -plot for your whole dataset. One way to solve your question is to add additional point-layers with subsets.

You didn't provide an example dataset yet, so I used the iris dataset. I recolored smaller and higher values of Sepal.Length by subseting the dataset and added points in blue. Futhermore small values in Sepal.Width got the color green.

To transfer this code to your case. Filter your dataset for your desired LogFC and/or P.Value and add these datasets and a color argument to additional geom_point layers.

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(color = "red") +
  geom_point(data = iris[iris$Sepal.Length < 5 | iris$Sepal.Length > 7, ], color = "blue") +
  geom_point(data = iris[iris$Sepal.Width < 3, ], color = "green")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM