1

Im trying to combine two plots into the same plot in R. My code looks like this:

#----------------------------------------------------------------------------------------#
# RING data: Mikkel
#----------------------------------------------------------------------------------------#
# Set working directory
setwd("/Users/mikkelastrup/Dropbox/Master/RING R")

#### Read data & Converting factors ####
dat <- read.table("R SUM kopi.txt", header=TRUE)  
str(dat)
dat$Vial <- as.factor(dat$Vial)
dat$Line <- as.factor(dat$Line)
dat$rep <- as.factor(dat$rep)
dat$fly <- as.factor(dat$fly)  
str(dat)

mtdata <- droplevels(dat[dat$Line=="20",])
mt1data <- droplevels(mtdata[mtdata$rep=="1",])

tdata <- melt(mt1data, id=c("rep","Conc","Sex","Line","Vial", "fly"))
tdata$variable <- as.factor(tdata$variable)
tfdata <- droplevels(tdata[tdata$Sex=="f",])
tmdata <- droplevels(tdata[tdata$Sex=="m",])

####Plotting####

d1 <- dotplot(tfdata$value~tdata$variable|tdata$Conc, 
        main="Y Position over time Line 20 Female",
        xlab="Time", ylab="mm above buttom")
d2 <- dotplot(tmdata$value~tdata$variable|tdata$Conc, 
        main="Y Position over time Line 20 Male",
        xlab="Time", ylab="mm above buttom")

grid.arrange(d1,d2,ncol=2)

And that looks like this: enter image description here

Im trying to combine it into one plot, with two different colors for male and female, i have tried to write it into one dotplot separated by a , and or () but that dosen't work and when i dont split the data and use tdata instead of tfdata and tfmdata i get all the dots in the same color. Im open to suggestions, using another package or another way of plotting the data that still looks somewhat like this since im new to R

Community
  • 1
  • 1
Mikkel Astrup
  • 405
  • 6
  • 18
  • 1
    Welcome to SO! It's most helpful if you can give us a minimal reproducible example; this helps us give you better advice, plus you can often find your errors yourself by simplifying the situation. See recommendations [here](http://stackoverflow.com/q/5963269/210673). In this case, however, the answer is almost certainly obvious just by looking at your code. – Aaron left Stack Overflow Mar 14 '16 at 18:18

1 Answers1

4

All you need to do is to use the group parameter.

dotplot(value~variable|Conc, group=Sex, data=tdata,
        main="Y Position over time Line 20 All",
        xlab="Time", ylab="mm above buttom")

Also, don't use the $ notation in these functions; notice that you're using value from tfdata but value and variable from tdata. This is a problem because there's twice as many rows in tdata! Instead, use the data argument to specify which data frame to get the variables from.

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142