[R] how to plot two variables in a figure using ggplot2

Gullen, James (MDE) GullenJ at michigan.gov
Wed Dec 16 14:37:29 CET 2015


Greetings!

You don't specify what type of "figure" you're looking for...here are two possibilities to get you started:

As a note, it would have made things slightly easier if you had used dput() to provide the data to us. It took a little massaging in notepad before getting it into R.

#Read data from clipboard after removing blank line and column numbers in notepad...
mydata <- read.table(file="clipboard", sep=" ", header =TRUE)
str(mydata)

#Restructure the data to long for ggplot2...there are other ways to do this, also.
mydata2 <- data.frame(group=rep(c("OA","KA"),  each=9), xvar=rep(mydata$XX, times=2), yvar=c(mydata$OA, mydata$KA))

 #Look at format of the data
mydata2

#Now to the plotting...
require(ggplot2)

#You might want a barplot...
plot1 <- ggplot(data=mydata2, aes(x=xvar, y=yvar,group=group, fill=group)) +
  geom_bar(stat="identity", position="dodge") + ggtitle("Barchart of OA and KA")

plot1

#..or you might want a lineplot...
plot2 <-ggplot(data=mydata2, aes(x=xvar, y=yvar, group=group, colour=group)) +
  geom_line() + ggtitle("Linechart of OA and KA")

plot2

The line chart is very easy to do in ggplot2 even if you don't restructure the data to long format, if that is what you were looking for.

Hope this helps and best regards!

Jim Gullen, Ph.D
Higher Education Data Reporting Consultant
Office of Professional Preparation Services
Michigan Department of Education

Customer Service is a priority at the Michigan Department of Education - helping Michigan schools, families, and communities improve the achievement and well-being of ALL our children.



More information about the R-help mailing list