---
title: "Introduction to Data Visualization in R"
author: "Martin Schweinberger"
date: ""
output:
  bookdown::html_document2: default
bibliography: bibliography.bib
link-citations: yes
---


```{r uq1, echo=F, fig.cap="", message=FALSE, warning=FALSE, out.width='100%'}
knitr::include_graphics("https://slcladal.github.io/images/uq1.jpg")
```

# Introduction{-}


```{r diff, echo=FALSE, out.width= "15%", out.extra='style="float:right; padding:10px"'}
knitr::include_graphics("https://slcladal.github.io/images/g_chili.jpg")
```

This tutorial introduces data visualization using R and shows how to modify different types of visualizations in the `ggplot` framework in R. This tutorial is aimed at beginners and intermediate users of R with the aim of showcasing how to visualize data and how to adapt, change, and modify visualizations using the `ggplot` package in R. The aim is not to provide a fully-fledged guide but rather to show and exemplify some common methods in data visualization such as how to produce different types of visualizations, how to adapt the style of visualizations, and how to modify the look and content of the visualizations in R.

R offers a myriad of options and ways to visualize and summarize data which makes R an incredibly flexible tool. This introduction will focus on the three main frameworks for data visualization in R (base, lattice, and ggplot). It will show you how to modify your visualizations (e.g., changing axes and tick labels, change colors, and showing different plots in one window). 

This introduction focuses on general questions and ideas behind data visualization, including problems you may encounter and practical exercises in setting up graphs. How to create different types of plots is shown in [this tutorial](dviz.html).

This section highlights the different philosophies that underlie the different frameworks for data visualization in R. The major advantage of using R consists in the fact that the code can be stored,
distributed, and run very easily. This means that R represents a flexible framework for creating graphs that enables sustainable, reproducible, and transparent procedures. There are of course, multitudes of ways to visualize data that will not be covered in this tutorial. 


<div class="warning" style='padding:0.1em; background-color:#f2f2f2; color:#51247a'>
<span>
<p style='margin-top:1em; text-align:center'>
To be able to follow this tutorial, we suggest you check out and familiarize yourself with the content of the following **R Basics** tutorials:<br>
</p>
<p style='margin-top:1em; text-align:left'>
<ul>
  <li>[Getting started with R](https://ladal.edu.au/intror.html) </li>
  <li>[Loading, saving, and generating data in R](https://ladal.edu.au/load.html) </li>
  <li>[String Processing in R](https://ladal.edu.au/string.html) </li>
  <li>[Regular Expressions in R](https://ladal.edu.au/regex.html) </li>
  <li>[Handling tables in R](https://ladal.edu.au/table.html) </li>
</ul>
</p>
<p style='margin-top:1em; text-align:center'>
Click [**here**](https://ladal.edu.au/content/introviz.Rmd)^[If you want to render the R Notebook on your machine, i.e. knitting the document to html or a pdf, you need to make sure that you have R and RStudio installed and you also need to download the [**bibliography file**](https://slcladal.github.io/content/bibliography.bib) and store it in the same folder where you store the Rmd file.] to download the **entire R Notebook** for this tutorial.<br><br>
[![Binder](https://mybinder.org/badge_logo.svg)](https://binderhub.atap-binder.cloud.edu.au/v2/gh/SLCLADAL/interactive-notebooks-environment/main?urlpath=git-pull%3Frepo%3Dhttps%253A%252F%252Fgithub.com%252FSLCLADAL%252Finteractive-notebooks%26urlpath%3Dlab%252Ftree%252Finteractive-notebooks%252Fnotebooks%252Fintroviz_cb.ipynb%26branch%3Dmain)<br>
Click [**here**](https://binderhub.atap-binder.cloud.edu.au/v2/gh/SLCLADAL/interactive-notebooks-environment/main?urlpath=git-pull%3Frepo%3Dhttps%253A%252F%252Fgithub.com%252FSLCLADAL%252Finteractive-notebooks%26urlpath%3Dlab%252Ftree%252Finteractive-notebooks%252Fnotebooks%252Fintroviz_cb.ipynb%26branch%3Dmain) to open an interactive Jupyter notebook that allows you to execute, change, and edit the code as well as to upload your own data. <br>
</p>
<p style='margin-left:1em;'>
</p></span>
</div>

<br>

## Basics of data visualization{-}

On a very general level, graphs should be used to inform the reader about properties and relationships between variables. This implies that…

* graphs, including axes, must be labeled properly to allow the reader to understand the visualization with ease. 

* there should not be more dimensions in the visualization than there are in the data.

* all elements within a graph should be unambiguous.

* variable scales should be portrayed accurately (for instance, lines - which imply continuity - should not be used for categorically scaled variables).

* graphs should be as intuitive as possible and should not mislead the reader.


## Graphics philosophies{-}

The three main frameworks in which to create graphics are *basic* framework, the *lattice* framework, and the *ggplot* or *tidyverse* framework. These frameworks reflect the changing nature of R as a programming language (or as a programming environment). The so-called *base R* consists of about 30 packages that are always loaded automatically when you open R - it is, so to say - the default version of using R when nothing else is loaded. The *base R* framework is the oldest way to generate visualizations in R that was used when other packages did not exists yet. However, *base R* can and is still used to create visualizations although most visualizations are now generated using the *ggplot* or *tidyverse* framework. The *lattice* framework followed the *base R* framework and offered some advantages such as handy ways to split up visualizations. However, *lattice* was replaced by the *ggplot* or *tidyverse* framework because the latter are much more flexible, offer full control, and follow an easy to understand syntax.

We will briefly elaborate on these three frameworks before moving on.

### The base R framework{-}

The *base R* framework is the oldest of the three and is included in what is called the `base R` - a collection of about 30 packages that are automatically activated/loaded when you start `R`.  The idea behind the "base" environment is that the creation of graphics is seen in analogy to a painter who paints on an empty canvass. Each line or element is added to the graph consecutively which oftentimes leads to code that is very comprehensible but also very long.

### The lattice framework{-}

The *lattice* environment was a follow-up to the *base* framework and it complements it insofar as it made it much easier to display various variables and variable levels simultaneously. The philosophy of the lattice-package is quite different from the philosophy of *base*: whereas everything had to be specified in *base*, the graphs created in the *lattice* environment require only very little code but are therefore very easily created when one is satisfied with the design but very labor intensive when it comes to customizing graphs. However, *lattice* is very handy when summarizing relationships between multiple variable and variable levels.

### The ggplot framework{-}

The *ggplot* environment was written by [Hadley Wickham](http://hadley.nz/) and it combines the positive aspects of both the *base* and the *lattice* package. It was first publicized in the *gplot* and *ggplot1* packages but the latter was soon repackaged and improved in the now most widely used package for data visualization: the *ggplot2* package. The *ggplot* environment implements a philosophy of graphic design described in builds on *The Grammar of Graphics* by Leland Wilkinson [@wilkinson2012grammar].

The philosophy of *ggplot2* is to consider graphics as consisting out of basic elements (called *aesthetics* and they include, for instance, the data set to be plotted and the axes) and layers that overlaid onto the aesthetics. The idea of the *ggplot2* package can be summarized as taking "care of many of the fiddly details that make plotting a hassle (like drawing legends) as well as providing a powerful model of graphics that makes it easy to produce complex multi-layered graphics."

Thus, ggplots typically start with the function call (`ggplot`) followed by the specification of the data, then the aesthetics (`aes`), and then a specification of the type of plot that is created (`geom_line` for line graphs, `geom_box` for box plots, `geom_bar` for bar graphs, `geom_text` for text, etc.). In addition, ggplot allows to specify all elements that the graph consists of (e.g. the theme and axes). The underlying principle is that a visualization is build up by adding layers as shown below. 

```{r plot10, echo = F, message=F, warning=F}
#install.packages("ggplot2")
#install.packages("vip")
library(ggplot2)
library(vip)
pdat  <- base::readRDS(url("https://slcladal.github.io/data/pvd.rda", "rb"))
p1 <- ggplot(pdat) + 
  labs(title = "Layer 1")
p2 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  labs(title = "Layer 2")
p3 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point() + 
  labs(title = "Layer 3")  
p4 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point() +
  geom_smooth() +
  labs(title = "Layer 4")
p5 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point() +
  geom_smooth() +
  theme_bw() +
  labs(title = "Layer 5")
p6 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point(color = "gray20", alpha = .5) +
  geom_smooth(color = "red", linetype = "dotted", size = .5) +
  theme_bw() +
  labs(title = "Layer 6", subtitle = "My pretty graph!")
grid.arrange(p1, p2, p3, p4, p5, p6, nrow = 2)
```


As the ggplot framework has become the dominant way to create visualizations in R, we will only focus on this framework in the following practical examples.

## Preparation and session set up{-}

This tutorial is based on R. If you have not installed R or are new to it, you will find an introduction to and more information how to use R [here](https://slcladal.github.io/intror.html). For this tutorials, we need to install certain *packages* from an R *library* so that the scripts shown below are executed without errors. Before turning to the code below, please install the packages by running the code below this paragraph. If you have already installed the packages mentioned below, then you can skip ahead and ignore this section. To install the necessary packages, simply run the following code - it may take some time (between 1 and 5 minutes to install all of the libraries so you do not need to worry if it takes some time).

```{r prep1, eval = F, warning = F, message = F}
# install packages
install.packages("dplyr")
install.packages("stringr")
install.packages("ggplot2")
install.packages("vcd")
install.packages("SnowballC")
install.packages("tidyr")
install.packages("gridExtra")
install.packages("flextable")
install.packages("RColorBrewer")
# install klippy for copy-to-clipboard button in code chunks
install.packages("remotes")
remotes::install_github("rlesur/klippy")
```

Now that we have installed the packages, we activate them as shown below.

```{r prep2, message=FALSE, warning=FALSE, class.source='klippy'}
# activate packages
library(dplyr)
library(stringr)
library(ggplot2)
library(tidyr)
library(gridExtra)
library(flextable)
library(RColorBrewer)
# activate klippy for copy-to-clipboard button
klippy::klippy()
```

Once you have installed R and RStudio and initiated the session by executing the code shown above, you are good to go.

# Getting started{-}

Before turning to the graphs, we briefly inspect the data which is called `pdat` and it is based on the [*Penn Parsed Corpora of Historical English*](https://www.ling.upenn.edu/hist-corpora/) (PPC). The data contains the date when a text was written (`Date`), the genre of the text (`Genre`), the name of the text (`Text`), the relative frequency of prepositions in the text (`Prepositions`), and the region in which the text was written (`Region`). Furthermore, `GenreRedux` collapses the existing genres into five main categories (*Conversational*, *Religious*, *Legal*, *Fiction*, and *NonFiction*) while `DateRedux` collapses the dates when the texts were composed into five main periods (1150-1499, 1500-1599, 1600-1699, 1700-1799, and 1800-1913). We also factorize non-numeric variables. 

```{r prep3, message=FALSE, warning=FALSE}
# load data
pdat  <- base::readRDS(url("https://slcladal.github.io/data/pvd.rda", "rb"))
```

Let's briefly inspect the data.

```{r prep5, echo = F}
# inspect data
pdat %>%
  as.data.frame() %>%
  head(15) %>%
  flextable::flextable() %>%
  flextable::set_table_properties(width = .95, layout = "autofit") %>%
  flextable::theme_zebra() %>%
  flextable::fontsize(size = 12) %>%
  flextable::fontsize(size = 12, part = "header") %>%
  flextable::align_text_col(align = "center") %>%
  flextable::set_caption(caption = "First 15 rows of the pdat data.")  %>%
  flextable::border_outer()
```

We will now turn to creating the graphs.

# Creating a simple graph{-}

When creating a visualization with ggplot, we first use the function `ggplot` and define the data that the visualization will use, then, we define the aesthetics which define the layout, i.e. the x- and y-axes. 

```{r plot1}
ggplot(pdat, aes(x = Date, y = Prepositions))
```

In a next step, we add the geom-layer which defines the type of visualization that we want to display. In this case, we use `geom_point` as we want to show points that stand for the frequencies of prepositions in each text. Note that we add the geom-layer by adding a `+` at the end of the line!

```{r plot2}
ggplot(pdat, aes(x = Date, y = Prepositions)) +
  geom_point()
```

We can also add another layer, e.g. a layer which shows a smoothed loess line, and we can change the theme by specifying the theme we want to use. Here, we will use `theme_bw` which stands for the black-and-white theme (we will get into the different types of themes later).

```{r plot3, message=F, warning=F}
ggplot(pdat, aes(x = Date, y = Prepositions)) +
  geom_point() +
  geom_smooth(se = F) +
  theme_bw()
```

We can also store our plot in an object and then add different layers to it or modify the plot. Here we store the basic graph in an object that we call `p` and then change the axes names.  

```{r plot4}
# store plot in object p
p <- ggplot(pdat, aes(x = Date, y = Prepositions)) +
  geom_point() +
  theme_bw()
# add layer with nicer axes titles to p
p + labs(x = "Year", y = "Frequency")
```

We can also integrate plots into data processing pipelines as shown below. When you integrate visualizations into pipelines, you should not specify the data as it is clear from the pipe which data the plot is using.

```{r plot5, message=F, warning=F}
pdat %>%
  dplyr::select(DateRedux, GenreRedux, Prepositions) %>%
  dplyr::group_by(DateRedux, GenreRedux) %>%
  dplyr::summarise(Frequency = mean(Prepositions)) %>%
    ggplot(aes(x = DateRedux, y = Frequency, group = GenreRedux, color = GenreRedux)) +
    geom_line()
```

# Modifying axes and titles{-}

There are different way to modify axes, the easiest way is to specify the axes labels using `labs` (as already shown above). To add a custom title, we can use `ggtitle`.

```{r axes1}
p + labs(x = "Year", y = "Frequency") +
  ggtitle("Preposition use over time", subtitle="based on the PPC corpus")
```

To change the range of the axes, we can specify their limits in the `coord_cartesian` layer.

```{r axes2}
p + coord_cartesian(xlim = c(1000, 2000), ylim = c(-100, 300))
```

```{r axes3}
p + 
  labs(x = "Year", y = "Frequency") +
  theme(axis.text.x = element_text(face="italic", color="red", size=8, angle=45),
          axis.text.y = element_text(face="bold", color="blue", size=15, angle=90))
```


```{r axes4}
p + theme(
  axis.text.x = element_blank(),
  axis.text.y = element_blank(),
  axis.ticks = element_blank())
```


```{r axes5, message=F, warning=F}
p + scale_x_discrete(name ="Year of composition", limits=seq(1150, 1900, 50)) +
  scale_y_discrete(name ="Relative Frequency", limits=seq(70, 190, 20))
```



# Modifying colors{-}

To modify colors, you can include a color specification in the main aesthetics.

```{r colors1}
ggplot(pdat, aes(x = Date, y = Prepositions, color = GenreRedux)) +
  geom_point() 
```

Or you can specify the color in the aesthetics of the geom-layer.

```{r colors2}
p + geom_point(aes(color = GenreRedux))
```

To change the default colors manually, you can use `scale_color_manual` and define the colors you want to use in the `values` argument and specify the variable levels that want to distinguish by colors in the `breaks` argument. You can find an overview of the colors that you can define in R [here](http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf).


```{r colors3}
ggplot(pdat, aes(x = Date, y = Prepositions, color = GenreRedux)) +
  geom_point()  + 
  scale_color_manual(values = c("red", "gray30", "blue", "orange", "gray80"),
                       breaks = c("Conversational", "Fiction", "Legal", "NonFiction", "Religious"))
```

When the variable that you want to colorize does not have discrete levels, you use `scale_color_continuous` instead of `scale_color_manual`.

```{r colors4}
p + geom_point(aes(color = Prepositions)) + 
  scale_color_continuous()
```

You can also change colors by specifying color `palettes`. Color `palettes` are predefined vectors of colors and there are many different color `palettes` available. Below are some examples using the `Brewer` color palette.

```{r colors5}
p + geom_point(aes(color = GenreRedux)) + 
  scale_color_brewer()
```

```{r colors6}
p + geom_point(aes(color = GenreRedux)) + 
  scale_color_brewer(palette = 2)
```

```{r colors7}
p + geom_point(aes(color = GenreRedux)) + 
  scale_color_brewer(palette = 3)
```


We now use the `viridis` color palette to show how you can use another palette. The example below uses the viridis palette for a discrete variable (GenreRedux).

```{r colors8}
p + geom_point(aes(color = GenreRedux)) + 
  scale_color_viridis_d()
```

To use the viridis palette for continuous variables you need to use `scale_color_viridis_c` instead of `scale_color_viridis_d`.

```{r colors9}
p + geom_point(aes(color = Prepositions)) + 
  scale_color_viridis_c()
```

The `Brewer` color palette (see below) is the most commonly used color palette but there are many more. You can find an overview of the color palettes that are available [here](https://www.datanovia.com/en/blog/top-r-color-palettes-to-know-for-great-data-visualization/).

```{r colors10}
display.brewer.all()
```


# Modifying lines & symbols{-}

```{r shape1}
ggplot(pdat, aes(x = Date, y = Prepositions, shape = GenreRedux)) +
  geom_point() 
```

```{r shape2}
ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point(aes(shape = GenreRedux)) + 
  scale_shape_manual(values = 1:5)
```

Similarly, if you want to change the lines in a line plot, you define the `linetype` in the aesthetics.

```{r shape3, message=F, warning=F}
pdat %>%
  dplyr::select(GenreRedux, DateRedux, Prepositions) %>%
  dplyr::group_by(GenreRedux, DateRedux) %>%
  dplyr::summarize(Frequency = mean(Prepositions)) %>%
  ggplot(aes(x = DateRedux, y = Frequency, group = GenreRedux, linetype = GenreRedux)) +
  geom_line()
```

You can of course also manually specify the line types.

```{r shape4}
pdat %>%
  dplyr::select(GenreRedux, DateRedux, Prepositions) %>%
  dplyr::group_by(GenreRedux, DateRedux) %>%
  dplyr::summarize(Frequency = mean(Prepositions)) %>%
  ggplot(aes(x = DateRedux, y = Frequency, group = GenreRedux, linetype = GenreRedux)) +
  geom_line() +
  scale_linetype_manual(values = c("twodash", "longdash", "solid", "dotted", "dashed"))
```

Here is an overview of the most commonly used linetypes in R.

```{r shape5}
d=data.frame(lt=c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash", "1F", "F1", "4C88C488", "12345678"))
ggplot() +
scale_x_continuous(name="", limits=c(0,1)) +
scale_y_discrete(name="linetype") +
scale_linetype_identity() +
geom_segment(data=d, mapping=aes(x=0, xend=1, y=lt, yend=lt, linetype=lt))
```

To make your layers transparent, you need to specify `alpha` values.

```{r shape6}
ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point(alpha = .2)
```

Transparency can be particularly useful when using different layers that add different types of visualizations.


```{r shape7, message=F, warning=F}
ggplot(pdat, aes(x = Date, y = Prepositions)) + 
  geom_point(alpha = .1) + 
  geom_smooth(se = F)
```

Transparency can also be linked to other variables.

```{r shape8, message=F, warning=F}
ggplot(pdat, aes(x = Date, y = Prepositions, alpha = Region)) + 
  geom_point()
```
```{r shape9}
ggplot(pdat, aes(x = Date, y = Prepositions, alpha = Prepositions)) + 
  geom_point()
```

# Adapting sizes{-}

```{r size1, message=F, warning=F}
ggplot(pdat, aes(x = Date, y = Prepositions, size = Region, color = GenreRedux)) +
  geom_point() 
```

```{r size2}
ggplot(pdat, aes(x = Date, y = Prepositions, color = GenreRedux, size = Prepositions)) +
  geom_point() 
```


# Adding text{-}

```{r text1}
pdat %>%
  dplyr::filter(Genre == "Fiction") %>%
  ggplot(aes(x = Date, y = Prepositions, label = Prepositions, color = Region)) +
  geom_text(size = 3) +
  theme_bw()
```

```{r text2}
pdat %>%
  dplyr::filter(Genre == "Fiction") %>%
  ggplot(aes(x = Date, y = Prepositions, label = Prepositions)) +
  geom_text(size = 3, hjust=1.2) +
  geom_point() +
  theme_bw()
```
```{r text3}
pdat %>%
  dplyr::filter(Genre == "Fiction") %>%
  ggplot(aes(x = Date, y = Prepositions, label = Prepositions)) +
  geom_text(size = 3, nudge_x = -15, check_overlap = T) +
  geom_point() +
  theme_bw()
```


```{r text4}
pdat %>%
  dplyr::filter(Genre == "Fiction") %>%
  ggplot(aes(x = Date, y = Prepositions, label = Prepositions)) +
  geom_text(size = 3, nudge_x = -15, check_overlap = T) +
  geom_point() +
  theme_bw()
```


```{r text5}
ggplot(pdat, aes(x = Date, y = Prepositions)) +
  geom_point() +
  ggplot2::annotate(geom = "text", label = "Some text", x = 1200, y = 175, color = "orange") +
  ggplot2::annotate(geom = "text", label = "More text", x = 1850, y = 75, color = "lightblue", size = 8) +
    theme_bw()
```


```{r text6}
pdat %>%
  dplyr::group_by(GenreRedux) %>%
  dplyr::summarise(Frequency = round(mean(Prepositions), 1)) %>%
  ggplot(aes(x = GenreRedux, y = Frequency, label = Frequency)) +
  geom_bar(stat="identity") +
  geom_text(vjust=-1.6, color = "black") +
  coord_cartesian(ylim = c(0, 180)) +
  theme_bw()
```



```{r text7}
pdat %>%
  dplyr::group_by(Region, GenreRedux) %>%
  dplyr::summarise(Frequency = round(mean(Prepositions), 1)) %>%
  ggplot(aes(x = GenreRedux, y = Frequency, group = Region, fill = Region, label = Frequency)) +
  geom_bar(stat="identity", position = "dodge") +
  geom_text(vjust=1.6, position = position_dodge(0.9)) + 
  theme_bw()
```


```{r text8}
pdat %>%
  dplyr::filter(Genre == "Fiction") %>%
  ggplot(aes(x = Date, y = Prepositions, label = Prepositions)) +
  geom_label(size = 3, vjust=1.2) +
  geom_point() +
  theme_bw()
```


# Combining multiple plots{-}

```{r combine1}
ggplot(pdat, aes(x = Date, y = Prepositions)) +
  facet_grid(~GenreRedux) +
  geom_point() + 
  theme_bw()
```

```{r combine2}
ggplot(pdat, aes(x = Date, y = Prepositions)) +
  facet_wrap(vars(Region, GenreRedux), ncol = 5) +
  geom_point() + 
  theme_bw()
```

```{r combine3}
p1 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + geom_point() + theme_bw()
p2 <- ggplot(pdat, aes(x = GenreRedux, y = Prepositions)) + geom_boxplot() + theme_bw()
p3 <- ggplot(pdat, aes(x = DateRedux, group = GenreRedux)) + geom_bar() + theme_bw()
p4 <- ggplot(pdat, aes(x = Date, y = Prepositions)) + geom_point() + geom_smooth(se = F) + theme_bw()
grid.arrange(p1, p2, nrow = 1)
```

```{r combine4, message=F, warning=F}
grid.arrange(grobs = list(p4, p2, p3), 
             widths = c(2, 1), 
             layout_matrix = rbind(c(1, 1), c(2, 3)))
```

# Available themes{-}

```{r theme1}
p <- ggplot(pdat, aes(x = Date, y = Prepositions)) + geom_point() + labs(x = "", y= "") +
  ggtitle("Default") + theme(axis.text.x = element_text(size=6, angle=90))
p1 <- p + theme_bw() + ggtitle("theme_bw") + theme(axis.text.x = element_text(size=6, angle=90))
p2 <- p + theme_classic() + ggtitle("theme_classic") + theme(axis.text.x = element_text(size=6, angle=90))
p3 <- p + theme_minimal() + ggtitle("theme_minimal") + theme(axis.text.x = element_text(size=6, angle=90))
p4 <- p + theme_light() + ggtitle("theme_light") + theme(axis.text.x = element_text(size=6, angle=90))
p5 <- p + theme_dark() + ggtitle("theme_dark") + theme(axis.text.x = element_text(size=6, angle=90))
p6 <- p + theme_void() + ggtitle("theme_void") + theme(axis.text.x = element_text(size=6, angle=90))
p7 <- p + theme_gray() + ggtitle("theme_gray") + theme(axis.text.x = element_text(size=6, angle=90))
grid.arrange(p, p1, p2, p3, p4, p5, p6, p7, ncol = 4)
```


```{r theme2}
ggplot(pdat, aes(x = Date, y = Prepositions, color = GenreRedux)) +
  geom_point() + 
  theme(panel.background = element_rect(fill = "white", colour = "red"))
```

Extensive information about how to modify themes can be found  [here](https://ggplot2.tidyverse.org/reference/theme.html).

# Modifying legends{-}

```{r legend1}
ggplot(pdat, aes(x = Date, y = Prepositions, color = GenreRedux)) +
  geom_point() + 
  theme(legend.position = "top")
```

```{r legend2}
ggplot(pdat, aes(x = Date, y = Prepositions, color = GenreRedux)) +
  geom_point() + 
  theme(legend.position = "none")
```

```{r legend3}
ggplot(pdat, aes(x = Date, y = Prepositions, linetype = GenreRedux, color = GenreRedux)) +
  geom_smooth(se = F) +  
  theme(legend.position = c(0.2, 0.7)) 
```


```{r legend4, message=F, warning=F}
ggplot(pdat, aes(x = Date, y = Prepositions, linetype = GenreRedux, color = GenreRedux)) +
  geom_smooth(se = F) + 
  guides(color=guide_legend(override.aes=list(fill=NA))) +  
  theme(legend.position = "top", 
        legend.text = element_text(color = "green")) +
  scale_linetype_manual(values=1:5, 
                        name=c("Genre"),
                        breaks = names(table(pdat$GenreRedux)),
                        labels = names(table(pdat$GenreRedux))) + 
  scale_colour_manual(values=c("red", "gray30", "blue", "orange", "gray80"),
                      name=c("Genre"),
                      breaks=names(table(pdat$GenreRedux)),  
                      labels = names(table(pdat$GenreRedux)))
```


# Citation & Session Info {-}

Schweinberger, Martin. 2022. *Introduction to Data Visualization in R*. Brisbane: The University of Queensland. url: https://ladal.edu.au/introviz.html  (Version 2022.11.17).

```
@manual{schweinberger2022introviz,
  author = {Schweinberger, Martin},
  title = {Introduction to Data Visualization in R},
  note = {https://ladal.edu.au/introviz.html},
  year = {2022},
  organization = "The University of Queensland, School of Languages and Cultures},
  address = {Brisbane},
  edition = {2022.11.17}
}
```


```{r fin}
sessionInfo()
```

***

[Back to top](#introduction)

[Back to LADAL home](https://ladal.edu.au)

***

# References {-}


