-1

I am plotting a simple ggplot scatter plot of one variable against another, faceted into a third variable and coloured based on a fourth.

It is important for me to colour based on the fourth variable (rather than facet) so I can show clear overlap.

This is causing an issue, however, as I can't work out how to specify the order in which the colour variable are plotted.

So, for sake of example, if the variable by which I can colouring my data ("colvar") has four values ("A","B","C","D"), I would like to specify that "D" is plotted first, then "B" on top, then "A", then finally "C" on the very top, as currently "C" is hidden beneath the others.

I have tried simply splitting the dataframe and plotting each with a different geom_point() but then I get the issue that its not easy to facet them with a facet_wrap().

# Reproducible Example

A <- data.frame(1:10, 1:10, "Norman")
B <- data.frame(1:5, 1:5, "Bradley")
C <- data.frame(1:20, 1:20, "Jason")

names(B) <- names(A)
names(C) <- names(A)

df <- rbind(A,B,C)

names(df) <- c("X","Y","Z")

ggplot(df) +
  aes(X,Y) +
  geom_point(aes(colour = Z))

# In this case "Jason" is plotted on top and blocks out Norman and Bradley.
# Is there a way to plot Jason, then Norman, then Bradley (without using
# rbind in a different order?

Jack
  • 173
  • 8
  • 1
    Could you try the following before plotting `df <- df[order(df$colvar),]` and see if that helps? Potentially you would have to adjust/re-order the levels of `df$colvar` to suit your needs. – teunbrand May 07 '19 at 12:48
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Also, make sure don't put `$` inside `aes()` statements; it should just be `aes(varA, varB)` as a general rule of thumb – MrFlick May 07 '19 at 12:52
  • I have now provided a simple reproducible example. – Jack May 07 '19 at 13:13

1 Answers1

0

Maybe you're looking for geom_jitter?

require(tidyverse)

df %>%
  ggplot(aes(X, Y, color = Z)) + 
  geom_point() +
  geom_jitter()

enter image description here

DJV
  • 4,743
  • 3
  • 19
  • 34
  • That seems to let me change the colours (e.g. 0/red 1/green or 0/green 1 red) but not the relative order in which they are plotted (which one is "on top") when I've attempted it – Jack May 07 '19 at 13:17