Adding custom legend to fourfold()

Viewed 131

Does anyone know how to add custom legends to fourfold() from the vcd package?

I can add to fourfoldplot() in base using the legend() function, but I want to use the custom colours for OR≈1.0 and OR≠1.0 that comes with fourfold()

When I create a plot using fourfold() and then try to add a legend using legend() I get the following error...

Error in strwidth(legend, units = "user", cex = cex, font = text.font) :

plot.new has not been called yet

Here is an example:

# install.packages("vcd")
library(vcd)

x<-matrix(c(1146,210,471,897,
            669,687,809,559,
            761,595, 1030,338,
            1227,129,1306,62,
            844,737,773,370,
            1134,447,344,799,
            1001,580,790,353,
            1461,120,1072,71,
            820,837,797,270,
            866,791,612,455, 
            1370,287,421,646, 
            1583,74,950,117, 
            1462,1056,155,51, 
            1349,1169,129,77,
            1688,830,103,103, 
            2419,99,114,92),ncol=8,nrow=8)
x
x<-as.table(x)
x<-as.data.frame(x)

xarray<-array(x$Freq, dim=c(2,2,16))
xarray<-aperm(xarray,c(2,1,3))
dimnames(xarray)[[1]] <- c("No", "Yes")
dimnames(xarray)[[2]] <- c("No", "Yes")
dimnames(xarray)[[3]] <- c("Morning:Morning","Morning:Afternoon","Morning:Evening","Morning:Night-time",
                                 "Afternoon:Morning","Afternoon:Afternoon","Afternoon:Evening","Afternoon:Night-time",
                                 "Evening:Morning","Evening:Afternoon","Evening:Evening","Evening:Night-time",
                                 "Night-time:Morning","Night-time:Afternoon","Night-time:Afternoon","Night-time:Night-time")
names(dimnames(xarray)) <- c("Post", "Pre", "Time of day")

fourfold(xarray, c("#99CCFF", "#6699CC", "#999999", "#E69F00", "#56B4E9", "#009E73"), ticks = 0.25,
         main = "Did you usually train in the morning, afternoon, evening or night-time?", p_adjust_method="bon") 

legend("right",legend = c("Non Sig.","Sig"), fill = c("#E69F00", "#009E73"))
1 Answers

fourfold is done on grid, legend() does not work. You can try using grid_legend() from vcd:

library(vcd)

png("test.png",width=800,height=600)

fourfold(xarray, c("#99CCFF", "#6699CC", "#999999", "#E69F00", "#56B4E9", "#009E73"), 
ticks = 0.25,
main = "Did you usually train in the morning, afternoon, evening or night-time?", 
p_adjust_method="bon") 

grid_legend(0.9, 0.5, c(15, 15), c("#E69F00", "#009E73"),
c("Non Sig.","Sig"))
dev.off()

In the grid_legend() function, first two arguments are x and y, which is the relative position of the legend on the plotting device. So 0.9 would be like 90% to the right and 0.5 in the middle, height wise.

enter image description here

Related