nik nik - 1 year ago 69
R Question

how to write conditions that define what color each point should be

Here is an example data as @ Gregor suggested

df = data.frame(x = rnorm(10), y = rnorm(10))

but I want to plot left part of plot (below zero in another color) and right part of the figure in another color

So I tried to plot it with ggplot but I am stuck , any suggestion?

g <- ggplot(data=df, aes(x=df[,1], y=df[,2])) +
geom_point() +
xlim(c(-2, 2)) + ylim(c(0,8)) +
xlab("my x axis") + ylab(" my y axis") +
guides(colour = guide_legend(override.aes = list(shape=16)))

what I want is to be able to plot it like this using ggplot

Answer Source

Okay. Let's be clear that this isn't a ggplot question at all, but a question of how to write conditions that define what color each point should be.

Starting with your original color scheme - I think I've correctly interpreted it as this

res$my_grouping = with(res, ifelse(pvalue < 0.5 | abs(log2FoldChange) > 1, ifelse(pvalue < 0.5 & abs(log2FoldChange) > 1, 'both', 'one'), 'neither'))

Now let's paste on on whether it is positive or negtiave:

res$my_grouping = paste(ifelse(res$log2FoldChange < 0, 'neg', 'pos'), res$my_grouping, sep = ', ')

Then plot:

ggplot(data=res, aes(x = log2FoldChange, y = -log10(pvalue), color = my_grouping)) +
  geom_point() +
  xlim(c(-2, 2)) + ylim(c(0,8)) +
  labs(x = "log2 fold change", y = "-log10  p-value", color = 'key') +
  guides(colour = guide_legend(override.aes = list(shape=16)))

Yielding this:

enter image description here

You can customize the color values using scale_color_manual.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download