0

I have a line of code that I am running on some data to make a MDS plot. Lets start with the data first:

Data for MDS 1

Data for MDS 2

I am creating MDS plots using this line of code:

ggplot(mds, aes(X1,X2,color=Virus_Treatment,shape=Infection)) + geom_point(size=3) + ggtitle("MDS Plot") + theme(plot.title = element_text(lineheight=.8, face="bold"))

When I plot the data for MDS 1, it looks like this:MDS plot 1

When I plot the data for MDS 2, however, it looks like this: enter image description here

First issue: Why is the infection legend on top for MDS 1, and on bottom for MDS 2? I literally ran the same code on it, why is the legend changing it's behavior? I want consistency between these plots. Is there any way to specify how legends are ordered?

Second Issue: I want the colors to be consistent for the Virus_Treatment part. In MDS 2, there is 1 more type of data than in MDS 1, so that throws off the color consistency. Is there a way to either re-order the data for MDS 2 so that the new color is at the end of the list, or to set a static color set manually? I need to keep the colors the same across graphs, even if the number of colors being used is different.

Thanks in advance for any insight on this!

Adam Price
  • 810
  • 2
  • 11
  • 21
  • 1
    Color legends are determined based on the levels of the factor. Use `factor()` on `Virus_Treatment` in both data sets and specify the `levels` to be the complete list of unique values, in the order you want. – Gregor Thomas Jul 17 '17 at 16:56
  • 1
    You can set colors via `scale_color_manual`; see, e.g., [here](https://stackoverflow.com/questions/19068432/ggplot2-how-to-use-same-colors-in-different-plots-for-same-factor). I remember that legend order can be [secret and unpredictable](https://stackoverflow.com/a/11397958/2461552); see the "order" argument to `guide_legend` for controlling order. – aosmith Jul 17 '17 at 16:56

1 Answers1

0

Thanks to Gregor and aosmith for their answers. This is what I've done to fix these issues:

Virus_Treatments <- factor(mds$Virus_Treatment, 
    levels = c("ACali09_contact", "AChkShng113_principal", 
               "AShng113_principal", "mock_mock", "ACali09_principal"))

color_set = c("#F8766D", "#7CAE00", "#00BFC4", "#C77CFF", "#FF61C3")

ggplot(mds, aes(X1,X2,color=Virus_Treatments,shape=Infection)) + geom_point(size=3) + ggtitle("MDS Plot") + theme(plot.title = element_text(lineheight=.8, face="bold")) + guides(colour = guide_legend(order = 2), shape = guide_legend(order = 1)) + scale_colour_manual(values=color_set)
Adam Price
  • 810
  • 2
  • 11
  • 21