# NOT RUN {
# create list representing two legends
legends1 <- list(
legend = list(
colours = c('orange', 'chartreuse4', 'darkorchid4'),
labels = c('Group 1', 'Group 2', 'Group 3'),
border = c('orange', 'chartreuse4', 'darkorchid4'),
title = 'Legend #1'
),
legend = list(
colours = c('firebrick3', 'lightgrey'),
labels = c('Case', 'Control')
)
);
# create a legend grob using defaults
legend.grob1 <- legend.grob(
legends = legends1
);
tiff(
file.path(tempdir(),'legend_grob1.tiff'),
type = 'cairo',
width = 5,
height = 5,
units = 'in',
res = 800,
compression = 'lzw'
);
grid.draw(legend.grob1);
dev.off();
# create the same legend with some customizations
legend.grob2 <- legend.grob(
legends = legends1,
label.cex = 1.25,
title.cex = 1.25,
title.just = 'left',
title.fontface = 'bold.italic',
size = 4,
border = list(),
layout = c(2,1)
);
tiff(
file.path(tempdir(),'legend_grob2.tiff'),
type = 'cairo',
width = 5,
height = 5,
units = 'in',
res = 800,
compression = 'lzw'
);
grid.draw(legend.grob2);
dev.off();
# create a legend where the title is underlined (see ?plotmath), add space between rows
legends2 <- list(
legend = list(
colours = c('orange', 'chartreuse4', 'darkorchid4'),
labels = c('Group 1', 'Group 2', 'Group 3'),
title = expression(underline('Legend #1'))
),
legend = list(
colours = c('firebrick3', 'lightgrey'),
labels = c('A label', 'A longer label')
)
);
# create the new legend and use more complex border
legend.grob3 <- legend.grob(
legends = legends2,
border = list(col = 'blue', lwd = 2, lty = 3),
border.padding = 1.5,
between.row = 3
);
tiff(
file.path(tempdir(),'legend_grob3.tiff'),
type = 'cairo',
width = 5,
height = 5,
units = 'in',
res = 800,
compression = 'lzw'
);
grid.draw(legend.grob3);
dev.off();
# Make a legend where the size of boxes is customized
legends3 <- list(
legend = list(
colours = c('orange', 'chartreuse4', 'darkorchid4'),
labels = c('Group 1', 'Group 2', 'Group 3'),
title = 'Legend #1',
size = c(3,2,1)
),
legend = list(
colours = NULL,
labels = c('+', '-'),
border = 'transparent',
title = 'Disease status',
size = 0.5
)
);
legend.grob4 <- legend.grob(
legends = legends3
);
tiff(
file.path(tempdir(),'legend_grob4.tiff'),
type = 'cairo',
width = 5,
height = 5,
units = 'in',
res = 800,
compression = 'lzw'
);
grid.draw(legend.grob4);
dev.off();
# }
Run the code above in your browser using DataCamp Workspace