
We will discuss “(d) adjusting some guides (e.g., legends)”, adjusting font size, and “(e) mathematical expressions in plots”.
Part of the contents on adjusting “legends” and “font sizes” can be found in Chapter 6 of the book “ggplot2: elegant graphs for data analysis” by Hadley Wickham, and the rest are gathered from various online resources.

Brief syntax:
theme(
# Legend position: right, left, bottom, top, none
legend.position = "right",
# Legend background
legend.background = element_rect(fill, color, size, linetype),
# Legend direction and justification, i.e.,
# layout of items in legends ("horizontal" or "vertical")
legend.direction = NULL,
# Legend box, i.e.,
# arrangement of multiple legends ("horizontal" or "vertical")
legend.box = NULL
)
Plot displ vs hwy with shape=drv:
> library(ggplot2)
> p = ggplot(mpg,aes(displ,hwy,shape=drv)) + geom_point()
shape=drv, a legend with title drv will be createddrv> p

top, horizontal> p+theme(legend.position = "top",
+ legend.direction = "horizontal")

bottom, horizontal> p+theme(legend.position = "bottom",
+ legend.direction = "horizontal")

bottom, vertical> p+theme(legend.position = "bottom",
+ legend.direction = "vertical")

> p+theme(legend.position = "none")

key> # remove legend key background
> p + theme(legend.key = element_rect(fill=NA))

> # `shape` is the aesthetic and used by `labs`
> p+labs(shape = "Drive type")

Plot displ vs hwy with color = cyl and shape=drv:
> library(ggplot2)
> p = ggplot(mpg, aes(displ,hwy))+
+ geom_point(aes(color = cyl, shape = drv))
color and the other for shape> p

> # Align the 2 legends horizontally
> p+theme(legend.box = "horizontal")

guides> # Hide legend for `color` via `guides`
> p + guides(color = FALSE)

Brief synatx:
theme(
legend.text=element_text(size=NULL),
legend.title=element_text(size=NULL)
)
Replace NULL by a positive number
> p+theme(legend.text=element_text(size=14),
+ legend.title=element_text(size=20))

Brief syntax:
theme(
axis.text.x =element_text(size=10,angle=0),
axis.title.x =element_text(size=14,angle=30),
axis.text.y =element_text(size=10,angle=0),
axis.title.y =element_text(size=14,angle=-40),
strip.text=element_text(size=12,angle=0)
)
facet_wrap or facet_grid is used, and it annotates the levels of variabels used for groupingangle is used to rotate texts or labels; this is useful when texts or labels are longPlot displ vs hwy with shape = drv and facet cyl:
> library(ggplot2)
> p = ggplot(mpg, aes(displ,hwy))+
+ geom_point(aes(shape = drv))+
+ facet_wrap(~cyl)
cyl are values of cyl> p

> p + theme(axis.text.x =element_text(size=10,angle=-30),
+ axis.title.x =element_text(size=14,angle=15),
+ strip.text=element_text(size=12,angle = -20))

Math expressions do appear frequently in R plots. To show math expressions in plots, we
can consult the “plotmath documentation” at https://www.rdocumentation.org/packages/grDevices/versions/3.5.1/topics/plotmath
need the expression and paste commands
We will use
paste(..., sep = " ")
to create a string that contains plotmath syntax/commands, and
expression(...)
to convert it into a mathematical expression
plotmath syntaxplotmath shares some syntax/commands with latex. Here are some plotmath commands:
alpha, … , omega are for Greek symbols \(\alpha\), …, \(\omega\)x[y] represents \(x_{y}\), and x[y][z] represents \(x_{yz}\)x^2 represents \(x^2\)Use demo(plotmath) to get more commands/syntax
paste command> paste("x", "trial", sep="")
[1] "xtrial"
>
> paste("x", "trial", sep=" ")
[1] "x trial"
sep="": no space between “x” and “trial” when they are concatenatedsep=" ": use a space to seperate “x” and “trial” when they are concatenatedexpression command> s1 = expression(paste("the square root of 2 is ",sqrt(2),
+ sep=""))
> s2 = expression(paste("double subscript ", x[1][2],
+ sep=" "))
> library(ggplot2)
> d1 = data.frame(cbind(1:10,1:10)); names(d1) = c("x1","y2")
> p10 = ggplot(d1,aes(x1,y2))+geom_point()+xlab(s1)+ylab(s2)
> # view s1 and s2
> s1
expression(paste("the square root of 2 is ", sqrt(2), sep = ""))
> s2
expression(paste("double subscript ", x[1][2], sep = " "))
Note: the expressions “s1” and “s2” have not been processed when no plots that use them as labels are created
> p10

Plot displ vs hwy with coloring col = drv:
> library(ggplot2)
> p = ggplot(mpg, aes(displ,hwy))+geom_point(aes(col = drv))
drv has 3 levels “4”, “f” and “r”col, i.e., color or colourdrv> p # note legend title and key labels

drv to “\(\alpha_1\)”, “\(\beta^{2}\)” and “r”, respectivelycolor aesthetic> # map "4", "f" and "r" to expressions
> drvStg = c(expression(alpha[1]),expression(beta^2),
+ expression(r))
> # modify legend title
> p2c= p+labs(col=expression(paste("Legend ",zeta,sep="")))+
+ # modify legend key labels
+ scale_color_discrete(labels =drvStg)
> p2c

> library(ggplot2) # create based player
> p=ggplot(mpg,aes(displ,hwy))+geom_point()+facet_wrap(~drv);p

DF (a factor) with levels “\(\alpha_1\)”, “\(\beta^2\)” and “r”slice to check correctness of mapping> drvStg = c(expression(alpha[1]),expression(beta^2),
+ expression(r))
> mpg$DF = factor(mpg$drv, labels =drvStg)
>
> library(dplyr)
> # check if the levels are labelled correctly
> mpg %>% select(displ, hwy, DF, drv) %>%
+ group_by(drv) %>% slice(1)
# A tibble: 3 x 4
# Groups: drv [3]
displ hwy DF drv
<dbl> <int> <fct> <chr>
1 1.8 26 alpha[1] 4
2 1.8 29 beta^2 f
3 5.3 20 r r
Create plot and
labeller = label_parsed to parse expressions, which are levels of DFfacet_wrap with DF:> library(ggplot2)
> p5 = ggplot(mpg, aes(displ,hwy))+geom_point()+
+ facet_wrap(~DF,labeller = label_parsed)
Use ?ggplot2::labeller to get more information on labeller
> p5

Math expressions in strip texts of facet_grid:
cyl, to “\(\gamma_1\)”, “\(5^2\)”, “6” and “8”, respectivelyCF (a factor) with levels “\(\gamma_1\)”, “\(5^2\)”, “6” and “8”> cylStg = c(expression(gamma[1]),expression(5^2),"6","8")
> mpg$CF = factor(mpg$cyl, labels =cylStg)
> library(dplyr)
> # check if the levels are labelled correctly
> mpg %>% select(displ, hwy, CF, cyl) %>%
+ group_by(cyl) %>% slice(1)
# A tibble: 4 x 4
# Groups: cyl [4]
displ hwy CF cyl
<dbl> <int> <fct> <int>
1 1.8 29 gamma[1] 4
2 2.5 29 5^2 5
3 2.8 26 6 6
4 4.2 23 8 8
> # parse expressions for both faceting variables
> ggplot(mpg, aes(displ,hwy))+geom_point()+
+ facet_grid(CF~DF,labeller = label_parsed)

> # parse expression for `CF` only
> ggplot(mpg, aes(displ,hwy))+geom_point()+
+ facet_grid(CF~DF,labeller = labeller(CF=label_parsed))

ggplot2 twicksgeom_ + scale*manualManually specify shapes and line types:
> library(ggplot2)
> p5 = ggplot(mpg, aes(cty,hwy))+ facet_wrap(~cyl)+theme_bw()+
+ geom_point(aes(shape = drv,color=drv),size=1.2) +
+ scale_shape_manual(values=c(2,1,4))+
+ geom_line(aes(linetype = drv),size=0.3)+
+ scale_linetype_manual(values=rep("dotted",3))
geom_point+scale_shape_manual: manually specify shapes; points are assigned shapesgeom_line+scale_linetype_manual: manually specify line types: points are connected by linesshape = drv,color=drv and linetype = drv: 3 legends as 1 and by drvgeom_ + scale*manual> p5

The R packages grid and gridExtra can be used to combined two or more ggplot2 plots
> # create 2 plots
> p1 = ggplot(mpg, aes(cty,hwy))+geom_point()
> p2 = ggplot(mpg, aes(displ,hwy))+geom_point()
> # combine p1 and p2 into one plot and put them in a row
> library(gridExtra); grid.arrange(p1,p2,nrow=1)

The following have not been covered:
stat_XXXmarginInformation on the above can be found in the book “ggplot2: elegant graphs for data analysis” by Hadley Wickham, or in various online resources
> sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
other attached packages:
[1] knitr_1.29
loaded via a namespace (and not attached):
[1] Rcpp_1.0.4.6 rstudioapi_0.11 magrittr_1.5
[4] tidyselect_1.1.0 munsell_0.5.0 colorspace_1.4-1
[7] R6_2.4.1 rlang_0.4.6 dplyr_0.8.5
[10] stringr_1.4.0 tools_3.5.0 revealjs_0.9
[13] grid_3.5.0 gtable_0.3.0 xfun_0.15
[16] htmltools_0.5.0 ellipsis_0.3.0 assertthat_0.2.1
[19] yaml_2.2.1 digest_0.6.25 tibble_3.0.1
[22] lifecycle_0.2.0 crayon_1.3.4 farver_2.0.3
[25] purrr_0.3.4 ggplot2_3.3.2 vctrs_0.2.4
[28] glue_1.4.0 evaluate_0.14 rmarkdown_1.11
[31] labeling_0.3 stringi_1.4.6 compiler_3.5.0
[34] pillar_1.4.4 scales_1.1.1 pkgconfig_2.0.3