I'm trying to adapt some of the standard R graphics to the ggplot2
style. One of the charts I want to do this is the interaction graph in a linear model fit study.
The following data were taken from Example 9-1 in Douglas C. Montgomery's book Design and Analysis of Experiments, 6th Edition.
montgomery <- structure(list(Nozzle = c("A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2",
"A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A3", "A3", "A3",
"A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3",
"A3", "A3", "A3", "A3"), Speed = c("B1", "B1", "B1", "B1", "B1",
"B1", "B2", "B2", "B2", "B2", "B2", "B2", "B3", "B3", "B3", "B3",
"B3", "B3", "B1", "B1", "B1", "B1", "B1", "B1", "B2", "B2", "B2",
"B2", "B2", "B2", "B3", "B3", "B3", "B3", "B3", "B3", "B1", "B1",
"B1", "B1", "B1", "B1", "B2", "B2", "B2", "B2", "B2", "B2", "B3",
"B3", "B3", "B3", "B3", "B3"), Pressure = c("C1", "C1", "C2",
"C2", "C3", "C3", "C1", "C1", "C2", "C2", "C3", "C3", "C1", "C1",
"C2", "C2", "C3", "C3", "C1", "C1", "C2", "C2", "C3", "C3", "C1",
"C1", "C2", "C2", "C3", "C3", "C1", "C1", "C2", "C2", "C3", "C3",
"C1", "C1", "C2", "C2", "C3", "C3", "C1", "C1", "C2", "C2", "C3",
"C3", "C1", "C1", "C2", "C2", "C3", "C3"), Loss = c(-35, -25,
110, 75, 4, 5, -45, -60, -10, 30, -40, -30, -40, 15, 80, 54,
31, 36, 17, 24, 55, 120, -23, -5, -65, -58, -55, -44, -64, -62,
20, 4, 110, 44, -20, -31, -39, -35, 90, 113, -30, -55, -55, -67,
-28, -26, -62, -52, 15, -30, 110, 135, 54, 4)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -54L), .Names = c("Nozzle",
"Speed", "Pressure", "Loss"))
According to the traditional way of creating the chart I want, I need to run
interaction.plot(montgomery$Nozzle, montgomery$Speed, montgomery$Loss)
Icancreateasimilargraphusingggplot2
:
library(dplyr)library(ggplot2)interaction<-montgomery%>%select(Nozzle,Speed,Loss)%>%group_by(Nozzle,Speed)%>%summarise(Average=mean(Loss))ggplot(interaction,aes(x=Nozzle,y=Average,colour=Speed,group=Speed))+geom_line()
What I want now is to create a function called interaction.plot.ggplot2
that automatically makes the previous graphic. The problem is that I do not know how to call the columns for the dplyr
commands to prepare the data to be plotted.
interaction.plot.ggplot2 <- function(response, predictor, group, data){
interaction <- data %>%
select(predictor, group, response) %>%
group_by(predictor, group) %>%
summarise(average = mean(response))
p <- ggplot(interaction, aes(x=predictor, y=average, colour=group, group=group)) +
geom_line()
print(p)
}
interaction.plot.ggplot2(Loss, Nozzle, Speed, montgomery)
Error in eval(expr, envir, enclos) : object 'Nozzle' not found
What should I do to make my interaction.plot.ggplot2
function create the chart I want?