top of page

Line Graph with Two IVs

KEY:

ds = dataset you are currently using.

DV = dependent variable of interest

IV = independent variable of interest

 

Subject = name of subject number column 

XYXY = dummy name for a variable, matrix, or data frame into which you are moving information.

2x2 line charts require several steps. For ease of comprehension I will list them, and then list the code below.

(Step 1) Make sure your IVs are set to be "factors". Load "psych" library, and then use the "describeBy" function to extract means for each condition

(Step 2) "describeBy" combines the two IVs names. Split them and assign the names you would like to use in your figure

(Step 3) Create the Figure

Also note: The names you give to your levels of your IV will appear on the Figure. You should make them appropriate in your data set before starting.

___Step 1_____________________

ds$IV1 <- as.factor(ds$IV1)

ds$IV2 <- as.factor(ds$IV2)

library(psych)

XYXY<-describeBy(ds$DV,

group = ds$IV1 : ds$IV2,
mat = TRUE,
type = 2,
digits = 2)

_____________________________

___Step 2_____________________

XYXY$IV1_Name <-sub("[:].*", "", XYXY$group1)   
XYXY$IV2_Name <-sub(".*[:]", "", XYXY$group1)

notes:

(a) "IV1_Name" is the name you want to give to the IV. It will appear on the figure

(b) group1 is the name that "describeBy" will give to the column with your IVs

(c)   "[:].*", ""    is an example of regular expression. It means "take everything after the colon and replace it with nothing." 

_____________________________

___Step 3_____________________

​library(ggplot2)

ggplot(XYXY, aes(group=IV1_Name, y=mean, x=IV2_Name))+

geom_line(aes(linetype=IV1_Name))+

geom_point(aes(shape=IV1_Name), size = 3)+

theme_classic()+

geom_errorbar(aes (ymin = mean - se, ymax = mean + se, width = .2))+

coord_cartesian(ylim=c(####,####))+

ylab("Dependent Variable Description")

 

notes:

(a) "mean" and "se" should be column names in XYXY. If you renamed them, then change accordingly.

(b) "geom_line(aes(linetype=..." forces the lines to vary by group, and "geom_point(aes(shape=..." forces the dot markers to vary by group. Omit the "aes(XXX)" portion as desired. Alternatively, you might set "aes(color=IV1_Name)" in either to cause the difference to be in terms of color.

(c) "coord_cartesian" allows you to set the minimum and maximum values of the y-axis.

(d) "ylab" allows you to add a description of your DV, in place of the column name from XYXY

_____________________________

bottom of page